1

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.

user43953
  • 109
  • 11
  • 1
    You may need to `parse` and `eval`uate. If thee 'a' object is already defined `eval(parse(text = paste0("list(", arg, ")")))` – akrun Nov 25 '19 at 19:40
  • @akrun I tried parse and got the error " unexpected ',' " due to the nature of the text I'm working with here. Any tips? – user43953 Nov 25 '19 at 19:44
  • 1
    The reason is that the string `"list(a,1),list(a,2)"` needs to be either inside a `list` or `c`. For that purpose, you may need to `paste` as in the above comment updated. Without knowing your function, it is not clear about what you are doing – akrun Nov 25 '19 at 19:45
  • 1
    @akrun That worked! Thank you. The lesson for me is that bits of text need to be turned into something that can be evaluated, then I can use the `eval(parse())` approach you suggest. If you care about getting credit please post as answer and I'll tag it as such. Really appreciate the quick insight! – user43953 Nov 25 '19 at 19:52

1 Answers1

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, ")")))
akrun
  • 874,273
  • 37
  • 540
  • 662