How to create a matrix or list of results using a loop?

Viewed 73

I am performing a loop to compute the values of 4 expressions. My loop is:

for (i in c(1:14)){
 VV1a <- round((db$Ya1[i]^Comb$Sigma)+ (1/(exp(log(1/p1a)^Comb$Alpha)))*
                       ((db$Xa1[i]^Comb$Sigma)-(db$Ya1[i]^Comb$Sigma)),1)
 VV1b <- round((db$Yb1[i]^Comb$Sigma)+ (1/(exp(log(1/p1b)^Comb$Alpha)))*
                       ((db$Xb1[i]^Comb$Sigma)-(db$Yb1[i]^Comb$Sigma)),1)
 VV2a <- round((db$Ya2[i]^Comb$Sigma)+ (1/(exp(log(1/p2a)^Comb$Alpha)))*
                       ((db$Xa2[i]^Comb$Sigma)-(db$Ya2[i]^Comb$Sigma)),1)
 VV2b <- round((db$Yb2[i]^Comb$Sigma)+ (1/(exp(log(1/p2b)^Comb$Alpha)))*
                       ((db$Xb2[i]^Comb$Sigma)-(db$Yb2[i]^Comb$Sigma)),1)
 
 }

Now for each singular, I have 2105401 values. However, using this statement each time R overwrites the elements (of course). In the end, my elements (VV1a, ....) contain only the last loop (i.e. i = 14).

How do I keep all the computation? To be more specific: ideally, for each, I would like to have a vector of the values computed.

1 Answers

Use a list().

Assuming that you're doing different calculations for VV1a, VV1b, etc..., you could store, for every iteration i, the resulting array as a list.

results <- list()
for (i in c(1:14)){
 results[["VV1a"]][[i]] <- list(your_calculations_which_result_in_a_vector)
 ....
 
 }
Related