You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

丰度数据框按样地汇总物种数据及类型转换问题求助

按样地汇总物种丰度的问题解决

数据概况

数据框taxa_ab包含63个物种列(整数型)和1个plot样地列(字符型,编号1-6,每个样地对应9个亚样地,共54行),前18行3列数据如下:

> taxa_ab
    plot Sp1 Sp2
1   1    0   0
2   1    1   1              
3   1    0   0               
4   1    0   0               
5   1    0   0               
6   1    0   3               
7   1    0   0               
8   1    0   0               
9   1    0   4               
10  2    4   0               
11  2    0   0               
12  2    0   2               
13  2    0   0               
14  2    0   0               
15  2    0   0
16  2    0   2               
17  2    0   0               
18  2    0   0               

预期结果

按plot汇总各物种丰度,将plot设为行名,得到如下输出:

> ab_new
    Sp1 Sp2
1   1   8
2   4   4 

尝试的错误代码

使用aggregate时写法有误,未能得到正确结果:

ab_new <- taxa.ab[,-2] %>%
        aggregate(., by = plot, FUN = "sum")

数据结构

> str(taxa_ab)
'data.frame':   54 obs. of  64 variables:
 $ plot     : chr  "1" "1" "1" "1" ...
 $ Sp1      : int  0 1 0 0 0 0 0 0 0 0 ...
 $ Sp2      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Sp3      : int  0 0 0 1 0 0 1 2 1 1 ...

解决方案

方法1:dplyr管道写法(推荐)

修正管道逻辑,按plot分组后对所有物种列求和,最后转置行名:

library(dplyr)
library(tibble) # 提供column_to_rownames函数

ab_new <- taxa_ab %>%
  group_by(plot) %>%
  summarise(across(starts_with("Sp"), sum)) %>% # 对所有Sp开头的列求和
  column_to_rownames(var = "plot") # 将plot列设为行名

方法2:Base R的aggregate写法

正确使用aggregate的分组参数,再处理行名:

# 按plot分组,对所有列求和
agg_data <- aggregate(. ~ plot, data = taxa_ab, FUN = sum)
# 将plot设为行名并移除原列
rownames(agg_data) <- agg_data$plot
ab_new <- agg_data[, -1]

关键说明

  • 整数型丰度无需转换为数值型,sum函数可直接处理,不会破坏数据结构。
  • plot列的字符型属性不影响分组求和,转换为行名后会保留原编号格式。

内容的提问来源于stack exchange,提问作者Vero Piedra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:20:32