我有以下代码:
eval(substitute(list(x = y), list(x = "foo", y = "bar")))
返回list(x = "bar")
,即只替换值而不是标签。
如何使substitute()
替换标签,以便结果为list(foo = "bar")
。
答案 0 :(得分:4)
x
绑定名称。我们可以看到
as.list(substitute(list(x = y)))
# [[1]]
# list
#
# $x
# y
因此,在substitute
电话中更改名称并不是非常容易。但你可以做到
e <- substitute(list(x = y), list(y = "bar"))
names(e)[2] <- "foo"
eval(e)
# $foo
# [1] "bar"
或仅使用substitute
,您可以更改表达式以使用setNames
e <- substitute(setNames(list(y), x), list(x = "foo", y = "bar"))
eval(e)
# $foo
# [1] "bar"
但您也可以使用call
,这更容易
cl <- call("list", foo = "bar")
eval(cl)
# $foo
# [1] "bar"
答案 1 :(得分:0)
我想出了这个怪物:
eval(parse(text = eval(替换(paste0(“list(”,x,“=”“,y,”\“)”),list(x =“foo”,y =“bar” )))))