show me the principle behind the code of getting for loop output

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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top