aL3xa
aL3xa

Reputation: 36080

Create a parse-able string from a named list and function name

I have apparently a simple one that my grey matter currently refuses to grasp - say I have a list:

list(a = "foo", b = c("bar", "biz", "booze"))

and a function fn. How can I get a string like this:

"fn(a = \"foo\", b = c(\"bar\", \"biz\", \"booze\"))"

P.S.

I know I'll regret for asking this one in the morning...

Upvotes: 2

Views: 240

Answers (2)

Josh O'Brien
Josh O'Brien

Reputation: 162321

You could also manipulate the language objects directly, as described in Chapter 6 of the R Language Definition:

X <- quote(list(a = "foo", b = c("bar", "biz", "booze")))
X[[1]] <- quote(fn)  ## as.symbol("fn") would also work
deparse(X)
# [1] "fn(a = \"foo\", b = c(\"bar\", \"biz\", \"booze\"))"

Or, if your list is already stored in a named object, you can just use c() and as.call() to piece together the desired call:

ll <- list(a = "foo", b = c("bar", "biz", "booze"))
deparse(as.call(c(as.symbol("fn"), ll)))
# [1] "fn(a = \"foo\", b = c(\"bar\", \"biz\", \"booze\"))"

Upvotes: 3

joran
joran

Reputation: 173577

This should get you started, right...?

deparse(list(a = "foo", b = c("bar", "biz", "booze")),control = NULL)
[1] "list(a = \"foo\", b = c(\"bar\", \"biz\", \"booze\"))"

A more complete version, which I finished just as @aL3xa commented...

gsub("^list","fn",
    deparse(list(a = "foo", b = c("bar", "biz", "booze")),control = NULL))

Upvotes: 5

Related Questions