Saving results from for loop as a vector in r

后端 未结 3 604
孤街浪徒
孤街浪徒 2021-01-05 09:24

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

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

How do I save the results as a vector, inst

相关标签:
3条回答
  • 2021-01-05 09:37

    Following form can also be used:

    > my_vector = c()
    > for(i in 1:5)       my_vector[length(my_vector)+1] = i
    > my_vector
    [1] 1 2 3 4 5
    
    0 讨论(0)
  • 2021-01-05 09:38

    Alternatively

    my_vector = c()
    for(i in 1:5){my_vector=c(my_vector,i)}
    my_vector
    
    0 讨论(0)
  • 2021-01-05 09:48

    Calling print will always print the result of each iteration to the console. If you leave in the print command, then you might get unwanted output.

    Your main problem is that you did not initialize my_vector before the for loop. You could instead do the following and not get the print side-effect.

    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 just the same as doing the following with sapply, but in this case you need no 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
    
    0 讨论(0)
提交回复
热议问题