【问题标题】:aggregate over certain rows between matrices在矩阵之间的某些行上聚合
【发布时间】:2014-03-08 10:56:29
【问题描述】:

假设我有及时采样的物种栖息地丰度矩阵。我正在尝试找到一种巧妙的方法来聚合时间重复,创建单个物种丰度矩阵。

# Construct dummy data

mat1<-matrix(c(1,3,0,2,0,0,6,0,10,1), ncol=5, nrow=2)
mat2<-matrix(c(0,11,0,0,1,0,2,3,7,1), ncol=5, nrow=2)
mat3<-matrix(c(2,1,0,0,3,1,1,0,4,0), ncol=5, nrow=2)
colnames(mat1) <-c('sp1','sp2','sp3','sp4','sp5')
rownames(mat1) <- c('h1','h2')
colnames(mat2) <-c('sp1','sp2','sp3','sp4','sp5')
rownames(mat2) <- c('h1','h2')
colnames(mat3) <-c('sp1','sp2','sp3','sp4','sp5')
rownames(mat3) <- c('h1','h2')
# Special case when new species occur
mat4 <- matrix(c(2,1,0,0,3,1,1,0,4,0,6,3), ncol=6, nrow=2)
colnames(mat4) <-c('sp1','sp2','sp3','sp4','sp5','sp6')
rownames(mat4) <- c('h1','h2')

# Replicate matrices are within a list
l.mat<-list(mat1,mat2,mat3,mat4)

我的第一个想法是使用apply(margin=2)(但话又说回来,这些 matices 在一个列表中,lapply?)和colSums 但我还没有找到不对行求和的方法(栖息地) 在每个矩阵内,而是在每个矩阵之间,如下所示。此外,当一个新物种出现时,它应该出现在聚合矩阵中

# Desired output

# Aggregated matrix
   sp1 sp2 sp3 sp4 sp5 sp6
h1   5   0   7  10  25  6
h2  16   2   2   3   2  3

任何指点将不胜感激,谢谢!

【问题讨论】:

  • 你能澄清一下你的聚合吗?给定您的输入矩阵,我希望例如h1sp1 为 1+0+2+2 = 5;N h1sp3: 0+1+3+3 = 7;等等。
  • 对不起,你说得对。忘记包含mat4
  • @jO.,您能再次检查所需的输出吗?它仍然没有完全加起来。

标签: r list matrix aggregate


【解决方案1】:

如果你使用“reshape2”包,这很直接:

library(reshape2)
allMat <- do.call(rbind, lapply(l.mat, melt))
dcast(allMat, X1 ~ X2, fun.aggregate=sum)
#   X1 sp1 sp2 sp3 sp4 sp5 sp6
# 1 h1   5   0   7  10  25   6
# 2 h2  16   2   2   3   2   3

或者,现在我想起来了(因为lists 有一个melt 方法,你可以这样做:

dcast(melt(l.mat), X1 ~ X2, value.var="value", fun.aggregate=sum)

如果你想坚持使用基础 R,我还没有找到任何直接的东西。以下是我想出的与上述相同的两种方法:

基本选项 1

allMat <- do.call(rbind, lapply(l.mat, function(x) 
  cbind(id = rownames(x), stack(data.frame(x)))))
xtabs(values ~ id + ind, data = allMat)
#     ind
# id   sp1 sp2 sp3 sp4 sp5 sp6
#   h1   5   0   7  10  25   6
#   h2  16   2   2   3   2   3

基础选项 2

allMat <- do.call(rbind, lapply(l.mat, function(x) {
  cbind(expand.grid(dimnames(x)), value = as.vector(x))
}))
allMat
xtabs(value ~ Var1 + Var2, allMat)
#     Var2
# Var1 sp1 sp2 sp3 sp4 sp5 sp6
#   h1   5   0   7  10  25   6
#   h2  16   2   2   3   2   3

【讨论】:

  • 非常感谢!再次为所需输出的混乱感到抱歉。
  • @jO.,没问题。如果您不想使用任何包,我也在基础 R 中添加了几个选项。
【解决方案2】:
library(reshape2)
library(dplyr)
df = rbind(melt(mat1),melt(mat2),melt(mat3),melt(mat4))
sdf = df %.% group_by(Var1,Var2)%.%summarize(value=sum(value))
dcast(sdf, Var1~Var2)

会产生

  Var1 sp1 sp2 sp3 sp4 sp5 sp6
1   h1   5   0   7  10  25   6
2   h2  16   2   2   3   2   3

【讨论】:

  • 看起来你有一些不必要的步骤/包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 2013-02-05
  • 2018-06-28
  • 2019-06-15
相关资源
最近更新 更多