Home > Back-end >  What is the principle behind the code of getting "for loop" output
What is the principle behind the code of getting "for loop" output

Time:01-03

I'm quite confused about the principle of the code getting the result returned from running the for loop, which is x=c(x,i)

> x<-c()
  for(i in 1:5){
     x=c(x,i)
  }
>  x
 [1] 1 2 3 4 5

As what I have understood about for loop, I thought x=i would return the expected result, in this case it would be 1 2 3 4 5, but the return is 5, only showing result of the last round of loop, I'm wondering why x=c(x,i) can collect the result from each round of the loop? what the relationships between x, x in () and i? Like what is the process of value assgining between them? Hope someone can explain it. Thank you sooo much!!!

> x<-c()
  for(i in 1:5){
     x=i
  }
>  x
 [1] 5

CodePudding user response:

x=c(x,i) is collecting the data because of the function c which concatenates each new value i to the previously existing vector x.

If you want to get more insights as to what's going on inside the loop, you can use print(x), which will display the value of x at each iteration of the loop.

x<-c()
for(i in 1:5){
  x=c(x,i)
  print(x)
}

# [1] 1
# [1] 1 2
# [1] 1 2 3
# [1] 1 2 3 4
# [1] 1 2 3 4 5

At each iteration, x is being updated with a new value i. Without c, the previous values of x would be deleted from the vector x, as shown below.

x<-c()
for(i in 1:5){
  x=i
  print(x)
}
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5

As @user2554330 pointed out in the comments, it is easier to think about it when using <- instead of =, as c(x,i) is being stored into a new vector x. x is thus being overwritten at each iteration, which is why you get a different result with x = i.

  • Related