Search code examples
rloopsfor-loopstore

For loop only stores final result in R


I am trying to run a for loop in R which stores the result in a list. I cannot store the data in a matrix as my outputs vary in length. For example, the following code produces a list with all entries as 'NULL' apart from the last section.

for(i in 1:n) {
  time <- list()
  time[[i]] <- (sample(1:96, wb[i], replace=T, prob=weekday[,1]))
print(time)
}

However, if I do this, the result is what I want, but it is not stored, so I cannot use it later.

for(i in 1:n) {
   print(sample(1:96, wb[i], replace=T, prob=weekday[,1]))
}

Any help would be appreciated!


Solution

  • For added fun (and efficiency) you can try

    time <- lapply(1:n, function(i) sample(1:96, wb[i], replace=T, prob=weekday[,1]))