rlistdimensional

how to make a list for 3 dimensional data in R


i have a issue related to list()
i need to use 3 for loops to process data just like this

for(i in 1:10){  #it is number of data group
 for(j in 1:5){  #it is number of sub-data group
  for(k in 1:2){ #it is number of sub-data group
     1.data process<br>
     2.just want to make a list within information of i, j ,k

      mylist[i][j][k]

     #i tested some methods like this, but it does not work well<br>
 }
 }
}

Could you give me any ideas or solutions for this issue? Thank you


Solution

  • It's unclear exactly what is necessary, but a multi-dimensionsal collection of non-atomic objects could be done like this:

    lst <- lapply(1:10, function(i) {
      lapply(1:5, function(k) {
        lapply(1:2, function(k) {
          # do something here
          lm(mpg ~ cyl, data = mtcars)
        })
      })
    })
    

    Now to access the [i,j,k]th element, for example to get the summary of the linear model just made:

    i <- 3; j <- 2; k <- 1
    summary(lst[[i]][[j]][[k]])
    

    If you absolutely must create it with for loops (not recommended), it's recommended that you pre-populate an empty structure and fill in the holes:

    lst <- replicate(10, replicate(5, replicate(2, NULL, simplify = FALSE), simplify = FALSE), simplify = FALSE)
    for (i in 1:10) {
      for (j in 1:5) {
        for (k in 1:2) {
          lst[[i]][[j]][[k]] <- ...
        }
      }
    }