How to insert text into an R function?

ε祈祈猫儿з 提交于 2020-01-25 03:09:07

问题


Consider a function f() of a list of lists as follows:

out <- f(list_of_lists = list(list(a,1),list(a,2)))

I would like to call this function dynamically:

arg = "list(a,1),list(a,2)"
out <- f(list_of_lists = list(arg))

But that gives the error "arg number 1 is not a list object".

How can I make f() read the object arg as the raw text it contains?

In Stata I would use macros to insert the text into the function; in R this is proving hard.

The question is inspired by an application of the dataprep() function in the Synth package, which has arguments with this type of complex formatting.


回答1:


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 evaluation after parseing

eval(parse(text = paste0("list(", arg, ")")))


来源:https://stackoverflow.com/questions/59038978/how-to-insert-text-into-an-r-function

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