好记fortune(312)
The problem here is that the $ notation is a magical shortcut and like any other magic if used incorrectly
is likely to do the programmatic equivalent of turning yourself into a toad.
-- Greg Snow (in response to a user that wanted to access a column whose name is stored in y via x$y
rather than x[[y]])
R-help (February 2012)
你想要的[[不是$
gtData <- function(data,field,k){
a <- data[[field]]
}
粘贴在这里绝对是错误的。
编辑——部分匹配
如果您想允许部分匹配,您可以将exactfor设置[[为FALSE或NA。从?`[[`
值 NA 允许部分匹配,但在发生时会发出警告。值 FALSE 允许部分匹配而没有任何警告。
然后再次
x$name 等价于 x[["name", exact = FALSE]]。
根据您的评论。我认为您需要查看R 手册 2.1.8和Hadley 的 devtools wiki,了解函数参数和承诺的方式
Promise 对象是 R 的惰性求值机制的一部分。它们包含三个槽:一个值、一个表达式和一个环境。当一个函数被调用时,参数是匹配的,然后每个形式参数都绑定到一个 Promise。为该形式参数给出的表达式和一个指向调用该函数的环境的指针存储在 Promise 中。
在访问该参数之前,没有与该承诺关联的值。当参数被访问时,存储的表达式在存储的环境中被计算,并返回结果。结果也被 promise 保存了。替换函数将提取表达式槽的内容。这允许程序员访问与 promise 关联的值或表达式。
所以当你通过
gtData(data = mtcars, field = mpg)
参数data是一个promise,mtcars当它在函数中被访问时,它的值将是来自调用环境的对象。
如果field您想访问字符串"mpg"而不是调用环境中关联的值mpg,如手册中所建议的那样,惯用的方法是使用deparse(substitute())
例如
gtData <- function(data,field,k){
fieldChar <- deparse(substitute(field))
a <- data[[fieldChar]]
}
这样做的危险是,如果你认为你可以field在函数内访问,在这种情况下它会被评估,并且会给出一个错误(如果它在调用环境中不存在),或者可能是一个意外的值如果它被定义