Lesley.H - 4 years ago 69
R Question

# Calculate in deeper list levels R

Imagine, I have list of two levels:

``````lll <- list()
lll[[1]] <- list(1:10, 1:5, 1:2)
lll[[2]] <- list(10:20, 20:30)
lll
[[1]]
[[1]][[1]]
[1]  1  2  3  4  5  6  7  8  9 10

[[1]][[2]]
[1] 1 2 3 4 5

[[1]][[3]]
[1] 1 2

[[2]]
[[2]][[1]]
[1] 10 11 12 13 14 15 16 17 18 19 20

[[2]][[2]]
[1] 20 21 22 23 24 25 26 27 28 29 30
``````

I want calculate means of these sequences. I have written a little function, which works fine:

``````func <- function(list.list){
lapply(1:length(list.list), function(i) mean(list.list[[i]]))
}

lapply(lll, func)
``````

I don't like in this function, that I have to use anonymous function.
It gets even more complicated when I have list of 3 levels.

Maybe you know better ways to make calculations in which anonymous function would not be included? Should I use higher-order functions (
`Map`
,
`Reduce`
)?

I know how to write
`for`
cycle, but in this case it isn't an option.

Here's a possible solution (using rapply = recursive apply) working at any level of depth :

``````lll <- list()
lll[[1]] <- list(1:10, 1:5, 1:2)
lll[[2]] <- list(10:20, 20:30)

res <- rapply(lll,mean,how='replace')
> res
[[1]]
[[1]][[1]]
[1] 5.5

[[1]][[2]]
[1] 3

[[1]][[3]]
[1] 1.5

[[2]]
[[2]][[1]]
[1] 15

[[2]][[2]]
[1] 25
``````

Setting argument `how='unlist'` you will get :

``````res <- rapply(lll,mean,how='replace')
> res
[1]  5.5  3.0  1.5 15.0 25.0
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download