强制评估作为参数传递给函数的对象

Ric*_*rta 0 evaluation eval r

我想将对象的值作为参数传递给函数。

# This is my object
anObject <- "an_unkown_string"

# I would like to do the equivalent of: 
someFunc("an_unkown_string")

# .. by somehow calling on the object containing the string
someFunc( ??? (anObject) )
Run Code Online (Sandbox Code Playgroud)

例如,使用下面的示例函数(基于save()):

someFunc <- function(...) {
  names <- as.character(substitute(list(...)))[-1L]
  return(names)
}

# Ideally, the output would be:
someFunc( ??? (anObject) )
[1] "an_unkown_string"
Run Code Online (Sandbox Code Playgroud)

我无权修改someFunc 我已尝试以下操作,但没有成功。

 someFunc(Name_of_Object)
 someFunc(eval(Name_of_Object))
 someFunc(evalq(Name_of_Object))
 someFunc(force(Name_of_Object))
 someFunc(eval(parse(text=Name_of_Object)))
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

GSe*_*See 5

怎么样

> do.call(someFunc, list(anObject))
[1] "an_unkown_string"
Run Code Online (Sandbox Code Playgroud)

或者你可以做一个包装纸

myWrap <- function(...) {
  do.call(someFunc, as.list(...))
}

> myWrap(anObject)
[1] "an_unkown_string"
Run Code Online (Sandbox Code Playgroud)

另一种构建调用并对其进行评估的方法:

> call("someFunc", anObject)
someFunc("an_unkown_string")
> eval(call("someFunc", anObject))
[1] "an_unkown_string"
Run Code Online (Sandbox Code Playgroud)

我想我应该?do.call提一下

对于使用 do.call 计算的函数,某些函数(例如替代函数)的行为与从解释器计算的函数不同。精确的语义目前尚未定义并且可能会发生变化。

尽管如此,至少现在,anObject在构造调用时(在对callor的调用中do.call)对 进行评估,因此substitute找到“an_unknown_string”而不是“anObject”。