如何在多个矩阵上有效地应用函数-列均值 [英] How to efficiently apply a function on a number of matrices - mean of columns
问题描述
因此,我刚接触矩阵和函数,我正在尝试找出如何应用函数来计算多个矩阵的列均值的方法.
So I am new to working with matrices and functions and I am trying to work out how to apply a function to calculate the column means to multiple matrices.
这里有一些假人马场:
A <- matrix(c(1,2,3,4,5,6,7,8,9),nrow=3)
B <- matrix(c(9,8,7,6,5,4,3,2,1),nrow=3)
我有13个大矩阵,所有变量都不同,但是它们的维数相同.我想获取每个单独矩阵的列均值.我已经解决了如何针对单个矩阵执行此操作:
I have 13 large matrices all different variables, but they all have the same dimensions. I want to get the mean of the columns for each individual matrices. I have worked out how to do this for an individual matrix:
AA <- sapply(1:3, function(x) mean(A [,x], na.rm = TRUE))
但是,将其应用于我的所有矩阵可能要比将其写出十二次并获得单独的输出更有效的方法,即每个矩阵的列均值是多少?我已经看到一些使用矩阵列表的工作-这是正确的方法吗?抱歉,如果这是重复的话,我试图找到一个清晰的示例,但没有正确的正确答案(随时向正确的方向指点我).
But there is probably a more efficient way to apply this to all my matrices than writing this out a dozen times and get the individual outputs, i.e column means for each matrix separately? I have seen some work with using lists of matrices - is this the correct route to go? Apologies if this is a duplicate, i have tried to find a clear example with the correct answer to no avail (feel free to point me in the right direction).
推荐答案
我们将矩阵保存在list
中,使用vapply
遍历list
并获取colMeans
We keep the matrices in a list
, use vapply
to loop through the list
and get the colMeans
vapply(list(A, B), colMeans, numeric(3))
# [,1] [,2]
#[1,] 2 8
#[2,] 5 5
#[3,] 8 2
或使用aggregate
aggregate(do.call(rbind, list(A, B)), list(rep(1:2, each = 3)), FUN = mean)
或使用tidyverse
library(tidyverse)
list(A, B) %>%
map(~ .x %>%
as.data.frame %>%
summarise_all(mean))
#[[1]]
# V1 V2 V3
#1 2 5 8
#[[2]]
# V1 V2 V3
#1 8 5 2
tidyverse方式可用于不同目的.也可以按操作分组
The tidyverse way can be chained for different purposes. It can also be a group by operation
list(A, B) %>%
map_df(as.data.frame, .id = 'grp') %>%
group_by(grp) %>%
summarise_all(mean)
# A tibble: 2 x 4
# grp V1 V2 V3
# <chr> <dbl> <dbl> <dbl>
#1 1 2 5 8
#2 2 8 5 2
这篇关于如何在多个矩阵上有效地应用函数-列均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!