我注意到,有相当多的包允许您传递符号名称,这些名称在调用函数的上下文中甚至可能是无效的。我想知道这是如何工作的,以及如何在我自己的代码中使用它?
下面是一个使用ggplot2的示例:
a <- data.frame(x=1:10,y=1:10)
library(ggplot2)
qplot(data=a,x=x,y=y)
我的名称空间中不存在x
和y
,但ggplot理解它们是数据帧的一部分,并将它们的求值推迟到它们有效的上下文中。我也试过做同样的事情:
b <- function(data,name) { within(data,print(name)) }
b(a,x)
然而,这却不幸地失败了:
Error in print(name) : object 'x' not found
我做错了什么?这是怎么回事?
注意:this is a副本of Pass variable name to a function in r
发布于 2015-12-04 10:04:09
我最近发现了一种我认为更好的传递变量名的方法。
a <- data.frame(x = 1:10, y = 1:10)
b <- function(df, name){
eval(substitute(name), df)
}
b(a, x)
[1] 1 2 3 4 5 6 7 8 9 10
更新该方法使用非标准评估。我开始解释,但很快意识到Hadley Wickham做得比我好得多。阅读此http://adv-r.had.co.nz/Computing-on-the-language.html
发布于 2013-10-02 17:46:52
您可以使用match.call
执行此操作,例如:
b <- function(data,name) {
## match.call return a call containing the specified arguments
## and the function name also
## I convert it to a list , from which I remove the first element(-1)
## which is the function name
pars <- as.list(match.call()[-1])
data[,as.character(pars$name)]
}
b(mtcars,cyl)
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
解释:
match.call返回一个调用,其中所有指定的参数都由它们的全名指定。
所以这里match.call
的输出是2个符号:
b <- function(data,name) {
str(as.list(match.call()[-1])) ## I am using str to get the type and name
}
b(mtcars,cyl)
List of 2
$ data: symbol mtcars
$ name: symbol cyl
因此,我使用第一个符号mtcar,并将第二个符号转换为字符串:
mtcars[,"cyl"]
或等同于:
eval(pars$data)[,as.character(pars$name)]
发布于 2019-10-25 03:48:40
非常旧的线程,但您也可以使用get
命令。它似乎对我更有效。
a <- data.frame(x = 1:10, y = 11:20)
b <- function(df, name){
get(name, df)
}
b(a, "x")
[1] 1 2 3 4 5 6 7 8 9 10
https://stackoverflow.com/questions/19133980
复制相似问题