Reputation: 1446
Older post:
I am wondering if it is possible to apply a function in different levels of a nested list, rapply
applies a function recursively in a list but in the same level. My question is related to apply a function in different levels with different lengths. An example for illustration:
list <- list(list(a=1:5, b=5:9, c=6:10, d=1:5),
list(e=2:6, f=3:7, g=8:12),
list(h=3:7, i=6:10, j=11:15, k=2:6),
list(l=4:8, m=2:6),
list(n=5:9, o=1:5, p=2:6, q=0:4),
list(r=6:10, s=3:7, t=9:13))
I would like to apply a function, such as sum
, to the first elements (e.g [[1]]$a=1, [[1]]$b=5, [[1]]$c=6, [[1]]d=1
, then to the second ones (e.g [[1]]$a=2, [[1]]$b=6, [[1]]$c=7, [[1]]$d=2)
and so on. The result should be something like that:
[[1]]
13 17 21 25 29
[[2]]
13 16 19 22 25
[[3]]
22 26 30 34 38
[[4]]
6 8 10 12 14
[[5]]
8 12 16 20 24
[[6]]
18 21 24 27 30
Perhaps a combination of rapply
and mapply
?
Thanks
New post:
@G.Grothendieck already gave me a good solution for this chase however, I have other list with pvalues where I would like to apply more complex functions, e.g. mean
or other functions such as:
Fisher.test <- function(p) {
Xsq <- -2*sum(log(p))
p.val <- 1-pchisq(Xsq, df = 2*length(p))
return(p.val)
}
Reduce does not work as it does with functions like sum
or with f="+"
, any suggestions??
Here is an example how this new list looks like"
pval.list <- list(list(a=c(0.05, 0.0001, 0.32, 0.45), b=c(0.1,0.12,0.01,0.06), c=c(0.1,0.12,0.01,0.06), d=c(0.01,0.02,0.03,0.04)),
list(e=c(0.04, 0.1, 0.232, 0.245), f=c(0.05, 0.01, 0.22, 0.54), g=c(0.005, 0.1, 0.032, 0.045)),
list(h=c(0.03, 0.01, 0.12, 0.4), i=c(0.5, 0.0001, 0.132, 0.045), j=c(0.005, 0.0001, 0.0032, 0.045), k=c(0.5, 0.1, 0.932, 0.545)),
list(l=c(0.022, 0.0012, 0.32, 0.45), m=c(0.0589, 0.0001, 0.0032, 0.0045)),
list(n=c(0.051, 0.01, 0.32, 0.45), o=c(0.05, 0.0001, 0.32, 0.45), p=c(0.05, 0.0001, 0.32, 0.45), q=c(0.05, 0.0001, 0.32, 0.45)),
list(r=c(0.053, 0.001, 0.32, 0.45), s=c(0.05, 0.0001, 0.32, 0.45), t=c(0.05, 0.0001, 0.32, 0.45)))
Upvotes: 4
Views: 1333
Reputation: 269481
Try this:
> lapply(list, Reduce, f = "+")
[[1]]
[1] 13 17 21 25 29
[[2]]
[1] 13 16 19 22 25
[[3]]
[1] 22 26 30 34 38
[[4]]
[1] 6 8 10 12 14
[[5]]
[1] 8 12 16 20 24
[[6]]
[1] 18 21 24 27 30
Upvotes: 4