问题
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