我希望我的循环使用计算值作为索引,但似乎不允许这样做。
这是示例代码:
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))
}
运行代码时,它没有使用rep
的新值rep + 6
。
我该怎么办?
Dixi
答案 0 :(得分:0)
要在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"