简体   繁体   中英

Output vector of loop function r

i´m trying to create an output vector of a loop, containing a result from each loop.

out=NULL
for (i in 1:5)  {
out<-cbind(out,sample(1:100, 1))  #placeholderfunction
for (i in 1:5) {out[i]<- i+1}  
}

The good side: My result contains the correct values. The bad side: it does as a matrix and i don´t know why.

> out
     out            
[1,]   2 71 14 46 96
[2,]   3 71 14 46 96
[3,]   4 71 14 46 96
[4,]   5 71 14 46 96
[5,]   6 71 14 46 96

What i want would be something like:

> out
     out            
[1,]   2 71 14 46 96

Probably it is just a small step from where i stand, but i just can´t figure it out, maybe someone could help? (and yes i could just remove but i would like my code clean)

Thanks!

Ok, by looking at the problem again on this scale i found it - a superfluous line:

> out=NULL
> for (i in 1:5)  {
+ out<-cbind(out,sample(1:100, 1))
+ }
> out
     [,1] [,2] [,3] [,4] [,5]
[1,]   63   98   78   43   19

What about this

 out <- sample(100,5)

Update

I see why I got a -1, the OP wants to construct a vector with a for loop. As a word of caution, creating a vector in this manner is usually not a good idea. For example, my above code is both simpler and faster than the OP's code. That withstanding, if you want generate a vector of random numbers with a for loop use this approach

my.loop <- function(l){
    out_1 <- numeric(l)
    for (i in 1:l)  {
        out_1[i] <- sample(1:100, 1)
    }
    out_1
}

This will be much better than op approach below because we are preallocating memory.

op.loop <- function(l){
    out_2 = NULL
    for (i in 1:l)  {
        out_2 <- cbind(out_2, sample(1:100, 1))
    }
    out_2
}

For fun I timed the two approaches:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM