R中矩阵列表的逐元素中位数

3

给定一个矩阵列表:

temp <- list(matrix(c(1,8,3,400), 2), 
    matrix(c(5,2,300,14),2), 
    matrix(c(100,200,12,4),2)
)
temp
# [[1]]
#      [,1] [,2]
# [1,]    1    3
# [2,]    8  400
#
# [[2]]
#      [,1] [,2]
# [1,]    5  300
# [2,]    2   14
#
# [[3]]
#      [,1] [,2]
# [1,]  100   12
# [2,]  200    4

我想要矩阵的逐元素中位数:

     [,1] [,2]
[1,]    5   12
[2,]    8   14

这能否在不使用显式for循环的情况下完成?

2个回答

6

首先,将它放入一个数组中:

library(abind)
a <- do.call(abind, c(temp, list(along=3)))

然后使用apply
apply(a, 1:2, median)
#      [,1] [,2]
# [1,]    5   12
# [2,]    8   14

正如@RichardScriven所建议的那样,您也可以在不使用abind包的情况下构建a
a <- array(unlist(temp), c(2, 2, 3))
# or
a <- array(unlist(temp), c(dim(temp[[1]]), length(temp)))

1
基本上,将其转换为3D数组,然后使用apply()函数。谢谢! - ved
2
可以通过 a <- array(unlist(temp), c(2, 2, 3)) 避免加载 abind - Rich Scriven

3
另一个选项是在将“temp”unlist后使用tapply
 res <- temp[[1]]
 res[] <- tapply(unlist(temp), rep(seq(length(temp[[1]])),length(temp)), FUN=median)
 res
 #     [,1] [,2]
 #[1,]    5   12
 #[2,]    8   14

或者另一种选择是,在将“temp”转换为 data.table setDT(temp))后,使用来自 library(matrixStats)的 rowMedians

 library(data.table)
 library(matrixStats)
 res[] <-  rowMedians(as.matrix(setDT(temp)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接