R 如何根据名称向量聚合列表中的矩阵?
我想根据存储在向量中的名称聚合(求和)列表中的矩阵。以下是一些示例数据:R 如何根据名称向量聚合列表中的矩阵?,r,list,aggregate,R,List,Aggregate,我想根据存储在向量中的名称聚合(求和)列表中的矩阵。以下是一些示例数据: lst <- list("111"=matrix(c(1, 0, 6, NA, 1, 0), nrow = 1, byrow = T), "112"=matrix(c(6, 2, 2, 0, 3, NA), nrow = 1, byrow = T),
lst <- list("111"=matrix(c(1, 0, 6, NA, 1, 0),
nrow = 1, byrow = T),
"112"=matrix(c(6, 2, 2, 0, 3, NA),
nrow = 1, byrow = T),
"113"=matrix(c(2, 3, 0, 0, 1, 1),
nrow = 1, byrow = T))
agg.nam <- c(111,113)
因此,第一个和第三个矩阵相加(na.rm=TRUE)
我首先尝试将agg.nam子集化:
lapply(lst, function(x) x[, which(names(x) %in% agg.nam)] )
但是我在这一点上已经失败了,没有聚合。您可以使用以下命令将相关列表元素抓取到矩阵中:
do.call(rbind, lst[as.character(agg.nam)])
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 0 6 NA 1 0
# [2,] 2 3 0 0 1 1
然后只需调用colSums
,使用na.rm=TRUE
(感谢@docendodiscimus指出这种简化):
如果矩阵有多行,上面的简化就不会真正起作用,下面的方法会更好:
# Grab relevant list elements
mats <- lst[as.character(agg.nam)]
# Replace any instance of NA with 0
mats <- lapply(mats, function(x) { x[is.na(x)] <- 0 ; x })
# Sum them up
Reduce("+", mats)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 3 3 6 0 2 1
#获取相关列表元素
mats1)abind即使组成矩阵不是单行矩阵,该功能也有效abind
从子列表L
创建一个三维数组,然后使用na.rm=TRUE
沿平行元素应用sum
library(abind)
L <- lst[as.character(agg.nam)]
apply(abind(L, along = 3), 1:2, sum, na.rm = TRUE)
2)数组这也可以工作,不使用任何包。除了使用array
将L
重塑为3d数组外,其工作原理相同<代码>L
来自上方
make3d <- function(List) array(unlist(List), c(dim(List[[1]]), length(List)))
apply(make3d(L), 1:2, sum, na.rm = TRUE)
3a)第(3)项的变化是:
苏姆纳
library(abind)
L <- lst[as.character(agg.nam)]
apply(abind(L, along = 3), 1:2, sum, na.rm = TRUE)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 3 6 0 2 1
make3d <- function(List) array(unlist(List), c(dim(List[[1]]), length(List)))
apply(make3d(L), 1:2, sum, na.rm = TRUE)
psum <- function(x, y) array(mapply(sum, x, y, MoreArgs = list(na.rm = TRUE)), dim(x))
Reduce(psum, L)
sumNA <- function(...) sum(..., na.rm = TRUE)
array(do.call(mapply, c(sumNA, L)), dim(L[[1]]))