[英]apply function in different levels of a nested list (re-post)
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. 我想知道是否可以在嵌套列表的不同级别中应用函数,
rapply
在列表中递归地应用函数但在同一级别。 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 (eg [[1]]$a=1, [[1]]$b=5, [[1]]$c=6, [[1]]d=1
, then to the second ones (eg [[1]]$a=2, [[1]]$b=6, [[1]]$c=7, [[1]]$d=2)
and so on. The result should be something like that: 我想将函数(例如
sum
)应用于第一个元素(例如[[1]]$a=1, [[1]]$b=5, [[1]]$c=6, [[1]]d=1
,然后是第二个(例如[[1]]$a=2, [[1]]$b=6, [[1]]$c=7, [[1]]$d=2)
依此类推。结果应该是这样的:
[[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
? 也许
rapply
和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, eg mean
or other functions such as: @Grothendieck已经为这个追逐给了我一个很好的解决方案,但是我有其他的pvalues列表,我想要应用更复杂的函数,例如
mean
或其他函数,例如:
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?? Reduce不能像
sum
或f="+"
这样的函数一样工作,有什么建议吗?
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)))
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.