Search code examples
rlistmatrixnestedindices

Reordering nested lists (index) according to colMeans of specific column in nested matrices


I'm working with a nested list of lists of matrices with doubles, motherlist.

m1<-matrix(rep(2+0.2*rnorm(3),5),5)
n1<-matrix(rep(5+2*rnorm(3),10),10)
p1<-matrix(rep(10+2*rnorm(3),8),8)
colnames(p1)<-colnames(m1)<-colnames(n1)<-c("a","b","c")
daughterlistl1<-list(m1,p1,n1)
daughterlistl2<-list(p1,n1,m1)
daughterlist3<-list(n1,m1,p1)
motherlist<-list(daughterlistl1, daughterlistl2, daughterlist3)

I want to take mean or colMeans of column "c" in each nested matrix (motherlist[[m]][[n]][,3]) and then reorder those matrices inside the nested list of matrices (motherlist[[m]][[n]]) (reorder n) ascendingly according to the mean value obtained, so that the matrix with smaller mean in the third column appears first, i.e. gets index 1 (motherlist[[m]][[1]]), and so on, for all m lists.

I was able to get the order of indices in one nested list

order(round(sapply(motherlist[[1]], colMeans), 3)[3,])

but not to reorder them in motherlist[[1]], nor do it iteratively for all m in motherlist.

is it possible to reassign indexes in a nested list? how? how can I recreate motherlist with ordered nested lists?


Solution

  • motherlist <- lapply(motherlist,function(y){
      y[order(sapply(y,function(x){mean(x[,3])}))]
    })
    

    Should work for your entire motherlist. The lacking function missing, when you have the indexes, is to use normal brackets:

    motherlist[[1]][order(round(sapply(motherlist[[1]], colMeans), 3)[3,])]
    

    gives what you want for thefirst list of your mother list. You just need to lapply again to loop over your motherlist