如何在 R 中获取点对点参数的名称

How to get names of dot-dot-dot arguments in R

如何获取包含传递给函数的点对点参数名称的字符向量,例如:

test<-function(x,y,...)
{
    varnames=deparseName(substitute(list(...)))
    # deparseName does not exist, this is what I want !
    # so that I could *for example* call:

    for(elt in varnames)
       {print(varnames);}
}

v1=11
v2=10
test(12,12,v1,v2)

## would print 
#v1
#v2

试试这个:

test<-function(x,y,...)
{
  mc <- match.call(expand.dots = FALSE)
  mc$...
}

v1=11
v2=10
test(12,12,v1,v2)
[[1]]
v1

[[2]]
v2

因此,match.call 的工作原理如下:

  • match.call()[[1]]return函数名

然后传递所有参数,所以 match.call()[[2]] 和 match.call()[[3]] return 第一个和第二个参数,与没有名称时的值(如此处):

test<-function(x,y,...) {
  list(
    match.call()[[1]],
    match.call()[[2]], 
    match.call()[[3]],
    match.call()[[4]],
    match.call()[[5]]
    )
}

v1=11
v2=10
test(12,12,v1,v2)
[[1]]
test

[[2]]
[1] 12

[[3]]
[1] 12

[[4]]
v1

[[5]]
v2

所以如果你需要,在这里,点,你可以这样做:

test<-function(x,y,...) {
  mc <- match.call()
  res <- c()
  for (i in 4:length(mc)){
    res <- c(res, mc[[i]])
  }
  res
}

您可以使用 deparsesubstitute 来获得您想要的(另请参阅 this Q&A):

test<-function(x, y, ...)
{
    varnames=lapply(substitute(list(...))[-1], deparse)
    lapply(varnames, print)
    return(invisible())
}

test(12,12,v1,v2)
#[1] "v1"
#[1] "v2"

为了稍微扩展其他答案,如果您只是想要传递给...的参数是名称,您可以使用is.name进行子集化在将它们分解为字符串之前未评估的点:

v1 <- 12
v2 <- 47
v3 <- "foo"

test <- function(x, y, ...){
    dots <- match.call(expand.dots = FALSE)$...
    dots <- dots[sapply(dots, is.name)]
    sapply(dots, deparse)
}

test(2, y = v1, z = v2, 1, v3)
#>    z      
#> "v2" "v3"