R:更改省略号中参数的值,并将省略号传递给另一个函数,而不使用list()和eval()

时间:2021-08-20 19:42:35

I am looking for a universal way to change a value of an argument inside ellipsis and pass it to the other function. I know an ugly solution for that, which looks like this:

我正在寻找一种通用的方法来更改省略号内的参数值并将其传递给另一个函数。我知道一个丑陋的解决方案,看起来像这样:

test <- function(...) {
  a <- list(...)
  a[['y']] <- 2
  return(eval(parse(text=paste0('identical(',paste(unlist(a),collapse=','),')'))))
}

test(x=1,y=1)

Ideally I would like to avoid converting ... to a list and then using eval(). Is it possible to somehow refer to an argument inside ... by name and change it's value?

理想情况下,我想避免将...转换为列表,然后使用eval()。是否有可能以某种方式引用...内部的参数并改变它的价值?

1 个解决方案

#1


9  

You do have to unpack ... to manipulate its contents. The ugly bit here, really, is your last line, which can be simplified to do.call(identical, a):

你必须解压缩...来操纵它的内容。这里的丑陋,真的,是你的最后一行,可以简化为do.call(相同,a):

test <- function(...) {
  a <- list(...)
  a[['y']] <- 2
  do.call(identical, a)
}

test(x=1,y=1)
# [1] FALSE

#1


9  

You do have to unpack ... to manipulate its contents. The ugly bit here, really, is your last line, which can be simplified to do.call(identical, a):

你必须解压缩...来操纵它的内容。这里的丑陋,真的,是你的最后一行,可以简化为do.call(相同,a):

test <- function(...) {
  a <- list(...)
  a[['y']] <- 2
  do.call(identical, a)
}

test(x=1,y=1)
# [1] FALSE