Search code examples
rfor-loopnestednested-for-loop

Storing a nested for loop into a single vector in R


Suppose I have the following code

b = 1:3
m = 5

for(j in 1:2){
  for(i in 1:5){
    print((1-i/m)* b[j] + (i/m)* b[j+1])
  }
}

If i print this i get the following output

[1] 1.2
[1] 1.4
[1] 1.6
[1] 1.8
[1] 2
[1] 2.2
[1] 2.4
[1] 2.6
[1] 2.8
[1] 3

However, now I would like to store this data into a single column vector. When i substitute print for an empty vector or list z[i] <- this ofcourse does not work. Does anyone know how to get the for loop value into a single column vector?


Solution

  • Base R, sapply

    b = 1:3
    m = 5
    
    df <- sapply(1:2,function(j){
      sapply(1:5,function(i){
        out <- (1-i/m)* b[j] + (i/m)* b[j+1]
        return(out)
      })
    })
    
    result <- c(df[c(1:5),c(1:2)]) 
    

    Result

    [1] 1.2 1.4 1.6 1.8 2.0 2.2 2.4 2.6 2.8 3.0
    

    Speed test - sapply vs for loop

    b = 1:10001
    m = 5
    
    > system.time({ 
    + df <- sapply(1:10000,function(j){
    +   sapply(1:5,function(i){
    +     out <- (1-i/m)* b[j] + (i/m)* b[j+1]
    +     return(out)
    +   })
    + })
    + })
       user  system elapsed 
       0.19    0.00    0.19 
     
    > system.time({ 
    + out <- c()
    + for(j in 1:10000){
    +   for(i in 1:5){
    +     out <- c(out, (1-i/m)* b[j] + (i/m)* b[j+1])
    +   }
    + }
    + })
       user  system elapsed 
       3.00    0.02    3.02