Use replace () to replace label / argument name

I have the following code:

eval(substitute(list(x = y), list(x = "foo", y = "bar")))

Returns list(x = "bar"), i.e. only the value is replaced, but not the label.

How to substitute()replace the label so that the result is list(foo = "bar").

+4
source share
2 answers

xattached to a name. We can see that with

as.list(substitute(list(x = y)))
# [[1]]
# list
#
# $x
# y

Therefore, it is not so easy to change the name in the call substitute. But you can do

e <- substitute(list(x = y), list(y = "bar"))
names(e)[2] <- "foo"
eval(e)
# $foo
# [1] "bar"

or just substituteyou can change the expression to usesetNames

e <- substitute(setNames(list(y), x), list(x = "foo", y = "bar"))
eval(e)
# $foo
# [1] "bar"

But you can also use callthat easier

cl <- call("list", foo = "bar")
eval(cl)
# $foo
# [1] "bar"
+4
source

I came up with this monster:

eval (parse (text = eval (substate (paste0 ( "list (", x, "= \" ", y," \ ")" ), list (x = "foo", y = "bar" )))))

0

All Articles