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

在R语言中创建透视表,按物种汇总各站点数值的求助

R 按物种分组生成求和透视表实现方案

方法1:使用dplyr包实现(主流推荐方案)

首先构造你的示例数据:

df <- data.frame(
  Species = c("Species1", "Species2", "Species4", "Species2", "Species3", "Species2", "Species1"),
  Station1 = c(5, 10, 0, 20, 4, 6, 5),
  Station2 = c(5, 52, 3, 15, 5, 9, 10),
  Station3 = c(5, 0, 8, 5, 5, 2, 5)
)

执行分组求和操作:

library(dplyr)
result <- df %>%
  group_by(Species) %>%
  summarise(across(starts_with("Station"), sum))

代码说明:group_by(Species)指定按物种列分组,across(starts_with("Station"), sum)表示对所有列名前缀为Station的列执行求和运算,输出结果完全匹配你需要的透视表结构。

方法2:基础R原生实现(无需安装第三方包)

直接调用aggregate函数即可完成需求:

result <- aggregate(. ~ Species, data = df, FUN = sum)

代码说明:. ~ Species表示将除Species外的所有列,按Species分组执行sum求和运算,输出结果和dplyr方案完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:57:02