如何获取包含传递给函数的点-点-点参数名称的字符向量:
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
答案 0 :(得分:6)
尝试一下:
test<-function(x,y,...)
{
mc <- match.call(expand.dots = FALSE)
mc$...
}
v1=11
v2=10
test(12,12,v1,v2)
[[1]]
v1
[[2]]
v2
答案 1 :(得分:4)
您可以使用deparse
和substitute
来获取想要的东西(另请参见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"
答案 2 :(得分:2)
因此,match.call
的工作方式如下:
match.call()[[1]]
返回函数的名称然后所有的args都被传递,所以match.call()[[2]]和match.call()[[3]]返回1和2nd参数,如果没有名称则返回值(如此处所示) ):
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
}
答案 3 :(得分:2)
要稍微扩展一下其他答案,如果恰好希望将传递给名称的参数传递给...
,则可以使用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"