force-evaluate an object being passed as an argument to a function

筅森魡賤 提交于 2019-12-08 11:29:42

问题


I would like to pass the value of an object as an argument to a function.

# 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) )

For example, with the sample function below (based on save()):

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

# Ideally, the output would be:
someFunc( ??? (anObject) )
[1] "an_unkown_string"

I do not have access to modify someFunc I have tried the following, but with no success.

 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)))

Any help is appreciated.


回答1:


How about

> do.call(someFunc, list(anObject))
[1] "an_unkown_string"

Or you could make a wrapper

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

> myWrap(anObject)
[1] "an_unkown_string"

Another way to construct a call and evaluate it:

> call("someFunc", anObject)
someFunc("an_unkown_string")
> eval(call("someFunc", anObject))
[1] "an_unkown_string"

I suppose I should mention that ?do.call says

The behavior of some functions, such as substitute, will not be the same for functions evaluated using do.call as if they were evaluated from the interpreter. The precise semantics are currently undefined and subject to change.

Nevertheless, for now at least, anObject is evaluated when the call is constructed (in the call to call or do.call), so substitute finds "an_unknown_string" instead of "anObject".




回答2:


I'm puzzled. Why are you trying to make this more complex than it realy is?

someFunc <- function(obj) {
   return(obj)
 }

> someFunc(anObject)
[1] "an_unkown_string"


来源:https://stackoverflow.com/questions/13809790/force-evaluate-an-object-being-passed-as-an-argument-to-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!