首页 > 解决方案 > R:循环列表中的值

问题描述

我希望我的循环使用计算值作为索引,但它似乎不允许我这样做。

这是一个示例代码:

stype_rep <- c(6:10,11:15,31:35)

rep <- 6 #this can change


for (rep in stype_rep){

  print(sprintf("rep start loop: %s",rep))
  rep <- rep + 6 #this can change
  print(sprintf("rep added: %s", rep))

}

运行代码时,它没有使用 is 的新reprep + 6。我怎么做?

迪西

标签: rfor-loop

解决方案


要在循环vector外递归更改for,您需要使用索引。请看下面的代码:

rep <- c(6:10, 11:15, 31:35)

for (i in seq_along(rep)[-1] - 1){
  print(sprintf("rep start loop: %s",rep[i]))
  rep[i + 1] <- rep[i] + 6 #this can change
  print(sprintf("rep added: %s",rep[i]))
}

输出:

[1] "rep start loop: 6"
[1] "rep added: 6"
[1] "rep start loop: 12"
[1] "rep added: 12"
[1] "rep start loop: 18"
[1] "rep added: 18"
[1] "rep start loop: 24"
[1] "rep added: 24"
[1] "rep start loop: 30"
[1] "rep added: 30"
[1] "rep start loop: 36"

推荐阅读