I am trying to create a list of expressions, like:
expressions = list()
values = list(1, 2, 3)
for (i in 1:3) {
expressions[[i]] = substitute(print(values[[I]]))
}
The only problem is that eval(expressions[[1]])
, eval(expressions[[2]])
, and eval(expressions[[3]])
give the same result because i
is evaluated just in the end. I tried
for (i in 1:3) {
expressions[[i]] = substitute(print(values[[eval(I)]]))
}
But same results, also with Bang Bang operator. The evaluation is required to be after the loop.
Thanks!
I am trying to create a list of expressions, like:
expressions = list()
values = list(1, 2, 3)
for (i in 1:3) {
expressions[[i]] = substitute(print(values[[I]]))
}
The only problem is that eval(expressions[[1]])
, eval(expressions[[2]])
, and eval(expressions[[3]])
give the same result because i
is evaluated just in the end. I tried
for (i in 1:3) {
expressions[[i]] = substitute(print(values[[eval(I)]]))
}
But same results, also with Bang Bang operator. The evaluation is required to be after the loop.
Thanks!
Share Improve this question edited Mar 19 at 7:31 Darren Tsai 36.3k5 gold badges25 silver badges57 bronze badges asked Mar 17 at 11:34 AvishAvish 1061 gold badge1 silver badge6 bronze badges 3 |2 Answers
Reset to default 4The signature of this function is substitute(expression, env)
. The way to achieve the behaviour you desire is to pass an argument to the (somewhat confusingly named) second parameter:
env
: an environment or a list object.
This usage is shown in the second example in the docs. It's also more idiomatic here to use lapply()
, as you're iterating over every element of a list to create another list of the same length:
lapply(values, \(value) substitute(print(v), list(v = value)))
# [[1]]
# print(1)
# [[2]]
# print(2)
# [[3]]
# print(3)
You can use bquote
where the term wrapped in .()
is evaluated.
lapply(values, \(v) bquote(print(.(v))))
# [[1]]
# print(1)
#
# [[2]]
# print(2)
#
# [[3]]
# print(3)
I
a typo? Are you looking forsubstitute(print(values[[i]]), list(i = i))
? – Roland Commented Mar 17 at 11:44I
to lower casei
produces the unwanted output described in the question where each expression is evaluated with the final value ofi
(i.e. it prints3
for every expression in the list). – SamR Commented Mar 17 at 11:50