我试图在我的函数体内连接我函数的参数,以便在bode中进一步评估.我经历了许多代码改进试图解决问题,但不能.
Example:当提供函数调用时fun(x,y),我希望能够粘贴我输入的字符x, $以及我为y输入的字符,以调用数据集中的字段进行分析.因此,如果我car为参数x和toyota参数提供了字符y,我将获得car$toyota在函数体内使用的变量名.
我试过了:
gtData <- function(data,field,k)
d <- diff(data$field) ## I also tried sum(data$field) to eliminate issues with diff()
Run Code Online (Sandbox Code Playgroud)
但d评估为0 ##我知道这不是因为当我运行代码时,diff(car$toyota)我得到了正确的答案.我不认为它做我想做的事.我还尝试将参数粘贴到正文中,如下所示:
gtData(data,field,k)
a <- paste(data,"$",field)
Run Code Online (Sandbox Code Playgroud)
抱怨toyota不存在因为丰田不是数据集而是数据集中的字段.
我尝试了很多其他变种,似乎paste()不能做我想要它做的事情.
我想要得到的是字符串,car$toyota所以我可以将它作为变量进一步传递到身体进一步评估.
记住是件好事 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)
Run Code Online (Sandbox Code Playgroud)
你想要的[[不是$
gtData <- function(data,field,k){
a <- data[[field]]
}
Run Code Online (Sandbox Code Playgroud)
粘贴绝对是错误的.
编辑 - 部分匹配
如果你想允许部分匹配,可以设置exact为[[向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)
Run Code Online (Sandbox Code Playgroud)
参数data是一个promise,它将mtcars在函数内访问时将值作为调用环境中的对象.
如果field您想要访问字符串"mpg"而不是mpg在调用环境中关联的值,如手册中所建议的那样,使用的惯用方法是使用deparse(substitute())
例如
gtData <- function(data,field,k){
fieldChar <- deparse(substitute(field))
a <- data[[fieldChar]]
}
Run Code Online (Sandbox Code Playgroud)
执行此操作的危险将是,如果您当时认为您可以field在函数内访问,在这种情况下它将被评估,并将给出错误(如果它在调用环境中不存在),或者可能是非预期的值如果它被定义