Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving low level elements from complex list (R)

Tags:

command

list

r

Suppose you have the following rather complex list structure:

all_m<-list();clist1<-list();clist2<-list()
for (j in 1:3){ for (i in 1:5){
      m1<-matrix(rnorm(4,0,1),2,2)
      m2<-matrix(rnorm(9,0,1),3,3)
      m3<-matrix(rnorm(16,0,1),4,4)
      m4<-matrix(rnorm(25,0,1),5,5)
      all_m<-list(m1,m2,m3,m4)
      names(all_m)<-c('m1','m2','m3','m4')
      clist1[[i]]<-all_m
      clist2[[j]]<-clist1
    }}

How can I address and retrive all low level elements in clist2 that are of the same type, say $m2, and re-arrange them into an array?

I guess this is possible without at loop. I would be interested in a solution that uses one of R's control structures, indexing or alike.

like image 707
tomka Avatar asked Dec 07 '25 06:12

tomka


1 Answers

How about:

library(abind)
fun1 <- function(x) abind(lapply(x,'[[',"m2"),along=3)
abind(lapply(clist2,fun1),along=4)
like image 174
Ben Bolker Avatar answered Dec 08 '25 18:12

Ben Bolker