【问题标题】:Most efficient way to aggregate matrix based on grouping variable基于分组变量聚合矩阵的最有效方法
【发布时间】:2016-03-12 11:00:19
【问题描述】:

是否有更有效的方法来执行以下操作,即基于分组变量聚合矩阵?

mat <- matrix( sample(2:100, 50), ncol=10, nrow=5)
colnames(mat) <- c(LETTERS[1:10])
rownames(mat) <- 1:5
mat.m <- melt(mat)
mat.m$Group <- NA

df <- cbind( data.frame(ID=LETTERS[1:10]), data.frame(Group=c("Plant","Fish","Rodent","Fish","Rodent","Bird","Plant","Fish","Bird","Bird")))
df$ID <- as.character(df$ID)
df$Group <- as.character(df$Group)

for( i in 1:nrow(mat.m) ){
  for( j in 1:nrow(df) ){
    mat.m$Group[i] <- ifelse(mat.m$Var2[i]==df$ID[j], df$Group[j], mat.m$Group[i])
  }
} 

mat.agg <- dcast(mat.m, Var1~Group, fun.aggregate = sum)

mat.agg
   Bird Fish Plant Rodent
1  154  215    43     83
2  122   44   132    163
3  177  211   118    120
4  206  125    89     92
5  125  269   151    156

我有非常大的矩阵,所以我想知道是否有更有效的方法。

【问题讨论】:

    标签: r for-loop matrix aggregate grouping


    【解决方案1】:

    我们可以split'df'中的'Group'的'ID',循环通过listvapply根据'ID'子集'mat'的列,使用rowSums获取每一行的总和以获得matrix 作为输出。

    vapply(split(df$ID, df$Group), function(x) 
                 rowSums(mat[,x]), numeric(nrow(mat)))
    

    注意:split 方法速度很快,因为我们使用的是vapply,它也提高了效率。

    【讨论】:

    • 如果 df$ID 仅包含其中一个潜在组怎么办?然后我得到Error in rowSums(mat[, 1]) : 'x' must be an array of at least two dimensions
    • @jO。也许你需要rowSums(mat[,x, drop = FALSE])
    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 2018-09-25
    • 2020-01-25
    • 1970-01-01
    • 2017-11-10
    • 2015-10-20
    • 2015-12-22
    • 1970-01-01
    相关资源
    最近更新 更多