2

我显然有一个简单的,我的灰质目前拒绝掌握 - 比如说我有一个清单:

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

和一个函数fn。我怎样才能得到这样的字符串:

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

附言

我知道我会后悔早上问这个...

4

2 回答 2

5

这应该让你开始,对吧......?

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

一个更完整的版本,正如@aL3xa 评论的那样,我完成了......

gsub("^list","fn",
    deparse(list(a = "foo", b = c("bar", "biz", "booze")),control = NULL))
于 2012-09-24T02:21:55.733 回答
3

您也可以直接操作语言对象,如R 语言定义的第 6 章所述:

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\"))"

或者,如果您的列表已经存储在命名对象中,您可以使用c()andas.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\"))"
于 2012-09-24T03:09:00.207 回答