在使用...
提供的参数列表中简单的功能,有可能是该功能查找名来自调用传递的对象的环境?如果是这样,怎么样?R:获得在'传递的参数名称...`
这出现在问题printing matrices and vectors side by side的上下文中,但可能更一般。
在这种情况下,参数...
也可以包含字符串,但不需要名称。这里是我的MWE,我尝试使用deparse(substitute())
,但无济于事。
test_names <- function(...) {
# get arguments
args <- list(...)
chars <- sapply(args, is.character)
names <- sapply(args, function(x) if(is.character(x)) " " else deparse(substitute(x)))
names
}
测试:
A = matrix(c(0.5, 1, 3, 0.75, 2.8, 4), nrow = 2)
x = c(0.5, 3.7, 2.3)
y = c(0.7, -1.2)
b = A %*% x - y
> test_names(A, " * ", x, " - ", y, " = ", b)
[1] "X[[i]]" " " "X[[i]]" " " "X[[i]]" " " "X[[i]]"
>
我期望这个输出是长度为7的特征向量:
[1] "A" " " "x" " " "y" " " "b"
令人惊讶这里,结果是所有X[[i]]
,当有在任何地方都没有提到X
。
继@罗兰的答案,这似乎做什么,我想:
test_names2 <- function(...) {
argnames <- sys.call()
unlist(lapply(argnames[-1], as.character))
}
> test_names2(A, " * ", x, " - ", y, " = ", b)
[1] "A" " * " "x" " - " "y" " = " "b"
你得到那些从lapply。它不保留列表名称。 – Roland
编辑显示所需的输出 – user101089