Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

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]])
    }
  }
}
question from:https://stackoverflow.com/questions/66052581/store-results-within-a-for-loop-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...