重置R中的循环变量

时间:2017-03-23 17:45:38

标签: r loops

我在for循环中循环变量“i”,并希望根据if语句的结果将值重新分配给“i”。示例如下。

for (i in 1:nrow(df)) {
     if (df[i, 5] > 4) {
          i <- 1
     } else {
          df[i, 5] <- df[1, 5] - 1
     }
}

如果我多次手动运行脚本,脚本会按预期工作,但它似乎没有正确地重新分配和/或在循环中注册它。想法?建议?提前谢谢!

1 个答案:

答案 0 :(得分:2)

更改循环内i的值不会改变1:nrow(df)中的位置。我认为这很好地说明了:

counter = 1
for (i in 1:3) {
    cat("counter ", counter, "\n")
    cat("i starts as ", i, "\n")
    i = 7
    cat("i is is set to ", i, "\n\n")
    counter = counter + 1
}
# counter  1 
# i starts as  1 
# i is is set to  7 
# 
# counter  2 
# i starts as  2 
# i is is set to  7 
# 
# counter  3 
# i starts as  3 
# i is is set to  7 

也许你应该使用while循环?我认为这是你想要实现的目标,但是在你的问题中没有提供样本输入,解释或所需的输出,这只是一个猜测:

i <- 1
while (i <= nrow(df)) {
     if (df[i, 5] > 4) {
          i <- 1
     } else {
          df[i, 5] <- df[1, 5] - 1
          i <- i + 1
     }
}