[英]How to apply function by column to a list of matrices
How would I go about applying a function by column to a list of matrices? 我如何将列中的函数应用于矩阵列表? For example I have a list like below. 例如,我有一个如下所示的列表。
[[1]]
[[1]][[1]]
[,1] [,2] [,3]
[1,] "b" "c" "d"
[2,] "y" "y" "y"
[3,] "z" "z" "z"
[[1]][[2]]
[,1] [,2] [,3]
[1,] "b" "b" "c"
[2,] "c" "d" "d"
[3,] "y" "y" "y"
[4,] "z" "z" "z"
[[2]]
[,1] [,2]
[1,] "y" "z"
This works fine: 这很好用:
apply(p[[1]][[1]],2,gen.fmla,y="q")
[[1]]
log(q) ~ b + y + z
<environment: 0x920732c>
[[2]]
log(q) ~ c + y + z
<environment: 0x912e66c>
[[3]]
log(q) ~ d + y + z
<environment: 0x85b608c>
But I can't figure out how to apply it to the list. 但我无法弄清楚如何将它应用到列表中。 lapply alone doesn't work as it applies the function to the entire matrix. 单独使用lapply不起作用,因为它将函数应用于整个矩阵。 I was trying to use a combo of apply and lapply, but couldn't figure it out. 我试图使用apply和lapply的组合,但无法理解。
To get a better answer, you need to supply a reproducible example. 要获得更好的答案,您需要提供可重现的示例。 For a general answer to your problem, you can use lapply
twice. 对于您的问题的一般答案,您可以使用lapply
两次。 For example: 例如:
##Create some data
R> l = list()
R> l[[1]] = matrix(rnorm(10), 2); l[[2]] = matrix(rnorm(10), 2)*10
R> L = list()
R> L[[1]] = l; L[[2]] = l
R> f = function(l) lapply(l, apply, 2, sum)
R> lapply(L, f)
[[1]]
[[1]][[1]]
[1] 1.1923 0.5275 0.4957 0.6848 -0.2776
[[1]][[2]]
[1] -13.984 15.435 -16.362 8.799 4.186
<snip>
Or using the rapply
function: 或者使用rapply
函数:
#Gives the same as above
R> rapply(L, function(i) apply(i, 2, sum), how="replace")
Your problem is not simply addressed by lapply since it is not a simple list. lapply并不是简单地解决你的问题,因为它不是一个简单的列表。 The first element has two lists each of which has as its first element a matrix. 第一个元素有两个列表,每个列表的第一个元素是矩阵。 The second element is just a matrix. 第二个元素只是一个矩阵。 There is an rapply function, which could be used if you provide a sensible test case of list and function. 有一个rapply函数,如果你提供一个合理的列表和函数测试用例,可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.