如何按列将函数应用于矩阵列表
我将如何按列将函数应用于矩阵列表?例如,我有一个如下所示的列表。
[[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"
这工作正常:
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>
但我不知道如何将其应用到列表中。 lapply 单独不起作用,因为它将函数应用于整个矩阵。我试图使用 apply 和 lapply 的组合,但无法弄清楚。
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. I was trying to use a combo of apply and lapply, but couldn't figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了获得更好的答案,您需要提供一个可重现的示例。要获得问题的一般答案,您可以使用
lapply
两次。例如:或者使用
rapply
函数:To get a better answer, you need to supply a reproducible example. For a general answer to your problem, you can use
lapply
twice. For example:Or using the
rapply
function:您的问题不能简单地通过 lapply 解决,因为它不是一个简单的列表。第一个元素有两个列表,每个列表都有一个矩阵作为其第一个元素。第二个元素只是一个矩阵。有一个 rapply 函数,如果您提供列表和函数的合理测试用例,则可以使用该函数。
Your problem is not simply addressed by lapply since it is not a simple list. 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.