如何在R函数中插入文字? [英] How to insert text into an R function?
问题描述
考虑以下列表列表的函数 f()
:
Consider a function f()
of a list of lists as follows:
out <- f(list_of_lists = list(list(a,1),list(a,2)))
我想动态调用此函数:
arg = "list(a,1),list(a,2)"
out <- f(list_of_lists = list(arg))
但这会导致错误 arg number 1不是列表对象
。
如何我让 f()
读取对象 arg
作为其包含的原始文本吗?
How can I make f()
read the object arg
as the raw text it contains?
在Stata中,我将使用宏将文本插入到函数中;在R中,这很难证明。
In Stata I would use macros to insert the text into the function; in R this is proving hard.
这个问题是受 Synth中
程序包,其中包含具有这种复杂格式类型的参数。 dataprep()
函数的应用启发的
The question is inspired by an application of the dataprep()
function in the Synth
package, which has arguments with this type of complex formatting.
推荐答案
我们可以使用列表
或粘贴
c
取决于我们是否需要嵌套的列表
或连接列表
,然后在解析
ing
We can paste
with a list
or c
based on how whether we need a nested list
or concatenate the list
and then do the eval
uation after parse
ing
eval(parse(text = paste0("list(", arg, ")")))
这篇关于如何在R函数中插入文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!