简体   繁体   English

如何在R中的列表中的所有元素的每个元素上应用函数

[英]How to apply a function on every element of all elements in a list in R

I have a list containing matrices of the same size in R. I would like to apply a function over the same element of all matrices. 我有一个包含R中相同大小的矩阵的列表。我想对所有矩阵的相同元素应用一个函数。 Example: 例:

> a <- matrix(1:4, ncol = 2)
> b <- matrix(5:8, ncol = 2)
> c <- list(a,b)
> c
[[1]]
     [,1] [,2]
[1,]    1    3
[2,]    2    4

[[2]]
     [,1] [,2]
[1,]    5    7
[2,]    6    8

Now I want to apply the mean function and would like to get a matrix like that: 现在,我想应用均值函数,并希望得到一个像这样的矩阵:

      [,1] [,2]
[1,]    3    5
[2,]    4    6

One conceptual way to do this would be to sum up the matrices and then take the average value of each entry. 一种实现此目的的概念方法是对矩阵求和,然后取每个条目的平均值。 Try using Reduce : 尝试使用Reduce

Reduce('+', c) / length(c)

Output: 输出:

     [,1] [,2]
[1,]    3    5
[2,]    4    6

Demo here: 演示在这里:

Rextester 右旋酯

Another option is to construct an array and then use apply . 另一种选择是构造一个数组,然后使用apply

step 1: constructing the array. 步骤1:构造数组。
Using the abind library and do.call , you can do this: 使用abind库和do.call ,您可以执行以下操作:

library(abind)
myArray <- do.call(function(...) abind(..., along=3), c)

Using base R, you can strip out the structure and then rebuild it like this: 使用base R,您可以删除结构,然后像这样重建它:

myArray <- array(unlist(c), dim=c(dim(a), length(c)))

In both instances, these return the desired array 在这两种情况下,这些都返回所需的数组

, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

step 2: use apply to calculate the mean along the first and second dimensions. 步骤2:使用apply来计算第一维和第二维的均值。

apply(myArray, 1:2, mean)
     [,1] [,2]
[1,]    3    5
[2,]    4    6

This will be more flexible than Reduce , since you can swap out many more functions, but it will be slower for this particular application. 这将比Reduce更加灵活,因为您可以交换出更多的功能,但是对于特定的应用程序,它会更慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM