Reputation: 617
I have a list which contains again multiple lists of arrays. The goal is to calculate the mean values of each of the arrays for the the third dimension.
So when the array is of the dimensions c(54,71,360)
the resulting mean values should be a matrix of the dimensions c(54,71)
for every single member of the lists.
Here is some code to reproduce sample data:
######################### create sample data ###########################
# create empty list
list1 <- list()
# fill the list with arrays
for (i in 1:10) {
list1[[i]] <- array(sample(1:100, 600, replace=T), dim= c(54,71,360))
}
# create the big list
big_list <- list()
for (i in 1:8) {
big_list[[paste0("list", i)]] <- list1
}
I can achieve it using a for loop:
######################## way to do it with for loop ####################
for (i in 1:length(big_list)) {
for (j in 1:length(list1)) {
big_list[[i]][[j]] <- apply(big_list[[i]][[j]], 1:2, mean, na.rm= T)
}
}
I am sure there is a more elegant way using lapply
in a nested way or something that leads to the same result by just using one or two lines.
I have struggled finding a way to combine the lapply
command with apply/sapply/etc.
inside so that the arrays inside the single lists are approached properly. I guess lapply
is needed since I need the big lists of lists as outcome.
Anybody with an idea how to do that?
Upvotes: 0
Views: 413
Reputation: 1059
Yes, but you will need the concept of anonymous functions. In essence, you declare custom made function in the middle of a lapply
. This gives you the liberty of using indexing within lapply.
result = lapply(big_list, function(x) {
lapply(x, function(y) {
apply(y, 1:2, mean, na.rm= T)
}
)
}
)
Tough, I must say that at that point, lapplys are doing more harm to the clarity of the code than helping. So, I would actually stick to using for
.
If you can remove the nested list structure and recreate it, it might be easier create codes with lapply. But that's beyond the question, since you mentioned you have to keep it.
Upvotes: 1
Reputation: 9858
I think you can use purrr
and nested map()
s, which are similar to lapply
, but with clearer synthax
library(purrr)
map(1:8, ~map(1:10, ~ array(sample(1:100, 600, replace=T), dim= c(54,71,360))))
If you want you can keep using lapply
the base R synthax for anonnymous functions in a similar fashion:
lapply(1:8, \(x) lapply(1:10, \(y) array(sample(1:100, 600, replace=T), dim= c(54,71,360))))
Upvotes: 0