有人可以帮助我理解“ for”功能吗？

``````k <- 1
for (i in 1:3){
k <- k + 1
for (j in 1:2){
k = k * j
}
}
``````

4 个答案:

1. 最初k = 1;
2. 在外循环的第一次迭代中，k变为k（1）+ 1的当前值，因此k = 2。
3. 然后，将内环使得其第一次迭代，则j = 1和k = K（2）*∫（1），所以K = 2
4. 然后内环的第二次迭代中，J为2，k为2仍然，所以K = K（2）*∫（2），所以K = 4
5. 后，返回到外循环，其中i变为2且k = K（4）+ 1 => K = 5
6. 然后再次启动内部循环（重复步骤3和4）

``````     k <- 1    // K = 1
for (i in 1:3){ // all the content of this loop will be repeated 3 times because i is between 1 and 3 ( 1,2,3 ) = ( i=1, i=2 and i=3)
//First time with: i=1
k <- k+1 // K = 1 + 1 = 2
for (j in 1:2){ // all the content of this loop will be repeated 2 times ( with : j=1 and j=2)
//First time with j=1:
k <- k*j // k = 2*1 = 2
//Second time with j=2:
k <- k*j // k=2*2 = 4
}
}
//Second time with: i=2
k <- k+1 // K = 4 + 1 = 5
for (j in 1:2){ // all the content of this loop will be repeated 2 times ( with : j=1 and j=2)
//First time with j=1:
k <- k*j // k = 5*1
//Second time with j=2:
k <- k*j // k=5*2 = 10
}
}
//Third time with: i=3 - the last one because i is between 1 and 3 ( 1,2,3 )
k <- k+1 // K = 10 + 1 = 11
for (j in 1:2){ // all the content of this loop will be repeated 2 times ( with : j=1 and j=2)
//First time with j=1:
k <- k*j // k = 11*1
//Second time with j=2:
k <- k*j // k=11*2 = 22
}
}
``````

``````for ( i in 1:10 ){
print "hello";
}
``````

``````for ( i in 1:10 ){
print "hello";
i <- 11;
}
``````

``````k=1
1. For-loop (1:4)
k = 1 + 1   // k = 2
k = 2 + 2  // k = 4
k = 4 + 3   // k = 7
k = 7 + 4    // k = 11

k=11
2. For-loop (1:2)
k = k * 1   // k = 11
k = k * 2   // k = 22

k = 22
``````

`print`语句添加到循环中。这是一种可以调试的好方法，也是查看正在发生的事情的极好方法。如果您运行此程序，我认为它将帮助您理解。

``````k <- 1
for (i in 1:3){
print(sprintf("Outer loop: i = %s, k = %s", i, k))
k <- k + 1
print(sprintf("Added one, now k = %s", k))
for (j in 1:2){
print(sprintf("  Inner loop: j = %s, k = %s", j, k))
k = k * j
print(sprintf("  Multiplied, now k = %s", k))
}
}
``````

``````[1] "Outer loop: i = 1, k = 1"
[1] "Added one, now k = 2"
[1] "  Inner loop: j = 1, k = 2"
[1] "  Multiplied, now k = 2"
[1] "  Inner loop: j = 2, k = 2"
[1] "  Multiplied, now k = 4"
[1] "Outer loop: i = 2, k = 4"
[1] "Added one, now k = 5"
[1] "  Inner loop: j = 1, k = 5"
[1] "  Multiplied, now k = 5"
[1] "  Inner loop: j = 2, k = 5"
[1] "  Multiplied, now k = 10"
[1] "Outer loop: i = 3, k = 10"
[1] "Added one, now k = 11"
[1] "  Inner loop: j = 1, k = 11"
[1] "  Multiplied, now k = 11"
[1] "  Inner loop: j = 2, k = 11"
[1] "  Multiplied, now k = 22"
``````

``````k <- 1
for (i in 1:3){
k <- k + 1
k <- k * 2 ## equivalent to inner loop
}
``````