简体   繁体   中英

Store results within a for loop in r

I am trying to create a list of 4 datasets of different dimensions and store these results in data_m in order to have for example a dataset of dimension 50x20, one of 100x20, and so on... But every time that I run the code the I get that the data are rewritten and I get 4 datasets all equal and of dimensions equal to the last dimensions of the two for loops...

Hope that somebody can help me Thanks in advance

This is the code:

multinom <- list()
multinom_z <- list()
var_m <- list()
var_mzeros <- list()
data_m <- list()  
data_mzeros <- list()
for (i in 1:4){
  for (p in c(20, 50)){
    for (n in c(50, 100)){
      set.seed(123)
      prob <- rep(1/p, p)
      multinom[[i]] <- t(rmultinom(n, p, prob = prob))
      zeros <- matrix(0, n, 85*p/100)
      multinom_z[[i]] <- cbind(multinom[[i]], zeros)
      data_m[[i]] <- data.frame(multinom[[i]])
    }
  }
}

If you add print(i) to the inner loop you'll see that there are 16 loops run and not 4 as you're expecting for results. The code is generating four different data.frame but then the fourth data.frame is saved as the last iteration for each value of i .

This removes the i loop and saves the data.frame to the list by name

multinom <- list()
multinom_z <- list()
var_m <- list()
var_mzeros <- list()
data_m <- list()  
data_mzeros <- list()

set.seed(123)

for (p in c(20, 50)){
  for (n in c(50, 100)){
    prob <- rep(1/p, p)
    multinom<- t(rmultinom(n, p, prob = prob))
    zeros <- matrix(0, n, 85*p/100)
    multinom_z <- cbind(multinom, zeros)
    data_m[[sprintf('d%ix%i', p, n)]] <- data.frame(multinom)
  }
}

Showing output names and dimensions

> lapply(data_m, dim)
$d20x50
[1] 50 20

$d20x100
[1] 100  20

$d50x50
[1] 50 50

$d50x100
[1] 100  50

If preferring to keep the list by index and not use names, the following could be used within the loop

data_m[[length(data_m) + 1]] <- data.frame(multinom)

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