Saving results for a loop as a vector in r

I have the following for a loop that prints numbers from 1 to 10:

for (i in 1:10) {print (i) } 

How to save the results as a vector, and not just print them on the console?

If I try:

 my_vector <- for (i in 1:10) {print (i) } 

Then call my_vector , I get:

 NULL 
+5
source share
3 answers

A call to print will always output the result of each iteration to the console. If you leave the print command, you may get unwanted output.

The main problem is that you did not initialize my_vector before the for loop. Instead, you can do the following and not get the side effect of print .

 my_vector <- vector("numeric", 10L) for(i in 1:10) my_vector[i] <- i my_vector # [1] 1 2 3 4 5 6 7 8 9 10 

But note that this is exactly the same as doing the following with sapply , but in this case you do not need an declaration, and you can assign the result to a vector.

 my_vector2 <- sapply(1:10, function(x) x) my_vector2 # [1] 1 2 3 4 5 6 7 8 9 10 
+10
source

You can also use the following form:

 > my_vector = c() > for(i in 1:5) my_vector[length(my_vector)+1] = i > my_vector [1] 1 2 3 4 5 
0
source

As an alternative

 my_vector = c() for(i in 1:5){my_vector=c(my_vector,i)} my_vector 
0
source

Source: https://habr.com/ru/post/1204525/


All Articles