重置R中的循环变量 [英] Reset Loop Variable in R
问题描述
我正在for循环中遍历变量"i",并希望根据if语句的结果将值重新分配给"i".下面的示例.
I am looping through a variable "i" in a for loop and want to reassign a value to "i" based on the outcome of an if statement. Example below.
for (i in 1:nrow(df)) {
if (df[i, 5] > 4) {
i <- 1
} else {
df[i, 5] <- df[1, 5] - 1
}
}
如果我多次手动运行该脚本,该脚本将按预期工作,但是它似乎并未正确地重新分配我和/或在循环中将其注册.有想法吗?有什么建议吗?提前致谢!
The script works as expected if I manually run it multiple times, but it doesn't seem to be reassigning i correctly and/or registering it in the loop. Ideas? Suggestions? Thanks in advance!
推荐答案
在循环内更改 i
的值不会更改您在 1:nrow(df)中的位置
.我认为这很好地说明了这一点:
Changing the value of i
inside the loop won't change where you are in the 1:nrow(df)
. I think this illustrates nicely:
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
循环?我认为这是您要实现的目标,但是在您的问题中没有提供示例输入,解释或所需的输出,这只是一个猜测:
Maybe you should be using a while
loop? I think this is what you are trying to achieve, but with no sample input, explanation, or desired output provided in your question, it's just a guess:
i <- 1
while (i <= nrow(df)) {
if (df[i, 5] > 4) {
i <- 1
} else {
df[i, 5] <- df[1, 5] - 1
i <- i + 1
}
}
这篇关于重置R中的循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!