Home > Blockchain >  Apply function to a list of lists
Apply function to a list of lists

Time:02-10

I have a list of length 100. Each entry is itself a list containing 31 matrices with 10 rows and five columns.

>length(dati_fault)
[1] 100
> length(dati_fault[[1]])
[1] 31

I should get 100 averages of the variables summarizing the 31 matrices each element of the list

media_1<-list()
for(i in nrow(dati_fault)){
  for(j in nrow(dati_fault[[i]]))
  media_1[[i]]<-lapply(dati_fault, colMeans(j))
  
}
media_1

But I get nothing because the media_1 list remains empty

CodePudding user response:

you don't need for loops to do so. You can directly work with lapply:

lapply(dati_fault, \(x) colMeans(do.call(rbind, x)))

This does the following: for each entry of dati_fault (i.e. each sublist of 31 matrices) these matrices are bound together (using rbind) into one single matrix with 310 rows and 5 columns. Then, colMeans is applied to this matrix.

If you are not familiar with the shorthand notation for anonymous functions (i.e. \(x)) you can read about it here.

CodePudding user response:

sample data

dati_fault <- lapply(1:100, function(x) {
  rep(list(matrix(sample(50, replace = T), nrow = 10, ncol = 5)), 31)
})

case 1: calculate means for each matrix

# to get the colMeans of each matrix (100 * 31 mean vectors)
lapply(dati_fault, function(x) lapply(x, colMeans))

case 2: calculate the mean of all matrixes in same list

# to get the colMeans of all 31 matrixes together (100 mean vectors) 
lapply(dati_fault, function(x) colMeans(do.call(rbind, x)))
  • Related