强制评估作为参数传递给函数的对象 [英] force-evaluate an object being passed as an argument to a function

查看:83
本文介绍了强制评估作为参数传递给函数的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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"

我无权修改someFunc 我尝试了以下方法,但没有成功.

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

感谢您的帮助.

推荐答案

如何

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


我想我应该提到?do.call

对于某些使用do.call评估的功能,某些功能(例如替代功能)的行为将不同,就好像它们是从解释程序进行评估的一样.目前尚不确定确切的语义,并且可能会发生变化.

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.

尽管如此,至少到目前为止,在构造调用时(在对calldo.call的调用中)会评估anObject,因此substitute会找到"an_unknown_string"而不是"anObject".

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".

这篇关于强制评估作为参数传递给函数的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆