如何合并R数据框(df)指定行并对对应矩阵数值求和
方法1:基础R实现(推荐大型矩阵用,效率更高)
直接使用rowsum()函数,专门针对按分组对行求和的场景,运算速度远高于普通分组操作,适合大型ASV矩阵:
# 1. 构造示例数据 example.matrix <- structure(list(ASV1 = c(8L, 0L, 3L, 6L, 1L), ASV2 = c(1L, 4L, 9L, 3L, 2L), ASV3 = c(1L, 0L, 0L, 1L, 1L), ASV4 = c(0L, 0L, 2L, 3L, 0L), ASV5 = c(0L, 7L, 1L, 4L, 0L)), class = "data.frame", row.names = c("sample-1", "sample-2", "sample-3", "sample-4", "sample-5")) # 2. 定义行的分组规则,顺序和原数据行顺序一致 # 样本量较大时也可以用行名匹配:group = ifelse(rownames(example.matrix) %in% c("sample-1","sample-2","sample-3"), "group1", "group2") group <- c("group1", "group1", "group1", "group2", "group2") # 3. 按分组求和 result <- rowsum(example.matrix, group = group)
输出结果:
ASV1 ASV2 ASV3 ASV4 ASV5 group1 11 14 1 2 8 group2 7 5 2 3 4
完全符合预期计算结果。
方法2:tidyverse语法实现
如果习惯dplyr管道操作可以用这个方法:
library(dplyr) library(tibble) result <- example.matrix %>% rownames_to_column("sample") %>% # 把行名转成普通列 mutate(group = case_when( sample %in% c("sample-1","sample-2","sample-3") ~ "group1", sample %in% c("sample-4","sample-5") ~ "group2" )) %>% group_by(group) %>% summarise(across(starts_with("ASV"), sum)) %>% # 对所有ASV列求和 column_to_rownames("group") # 把分组名转回行名
输出结果和方法1完全一致。
内容的提问来源于stack exchange,提问作者Geomicro
相关产品推荐
相关产品推荐

