最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Substitute inside a loop - Stack Overflow

programmeradmin3浏览0评论

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 Is I a typo? Are you looking for substitute(print(values[[i]]), list(i = i))? – Roland Commented Mar 17 at 11:44
  • 1 @Roland I assumed that was the case as changing the upper case I to lower case i produces the unwanted output described in the question where each expression is evaluated with the final value of i (i.e. it prints 3 for every expression in the list). – SamR Commented Mar 17 at 11:50
  • 1 Hi, if any of the answers have solved your question, you can consider accepting the one that best meets your request by clicking the check mark. – Darren Tsai Commented Mar 20 at 6:50
Add a comment  | 

2 Answers 2

Reset to default 4

The 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)
发布评论

评论列表(0)

  1. 暂无评论