如何使用R将单叶独立测量数据汇总为单株总数据集
R 按植株汇总叶片质量解决方案
你的需求核心是按植株(Plant列)为分组维度,对Leaf.Mass列的叶片重量数值进行求和,以下是两种常用实现方案:
方法1:使用tidyverse生态的dplyr包(适配常规数据分析流程)
# 未安装dplyr的话先运行 install.packages("dplyr") library(dplyr) # 读入你的数据集,示例数据赋值给df df <- structure(list(Tray = c(1, 1, 1, 1, 1, 1), Plant = c(2, 2, 2, 2, 3, 3), Treatment = structure(c(4L, 4L, 4L, 4L, 4L, 4L), .Label = c("2TLH", "E2TL", "EH", "WL"), class = "factor"), PreSwitch = c("Soil", "Soil", "Soil", "Soil", "Soil", "Soil"), PostSwitch = c("Soil", "Soil", "Soil", "Soil", "Soil", "Soil"), Pellet = c(1, 1, 1, 1, 1, 1), Rep = c(1, 1, 1, 1, 1, 1), Date = structure(c(1618963200, 1618963200, 1618963200, 1618963200, 1618963200, 1618963200), tzone = "UTC", class = c("POSIXct", "POSIXt")), DAP = c(60, 60, 60, 60, 60, 60), Position = c(2, 1, 3, 4, 4, 3), Whorl = structure(c(1L, 1L, 2L, 2L, 2L, 2L), .Label = c("1", "2", "3", "4", "5"), class = "factor"), PetioleLength = c(1.229, 1.365, 1.713, 1.02, 0, 1.408), BladeLength = c(1.604, 1.755, 2.466, 2.672, 0.267, 2.662), BladeWidth = c(1.023, 1.185, 1.803, 1.805, 0.077, 1.771), BladeArea = c(1.289, 1.634, 3.492, 3.789, 0.016, 3.704), BladePerimeter = c(6.721, 7.812, 11.61, 12.958, 1.019, 14.863), BladeCircularity = c(0.359, 0.336, 0.326, 0.284, 0.196, 0.211), BPR = c(1.30512611879577, 1.28571428571429, 1.43957968476357, 2.61960784313725, NA, 1.890625), Leaf.Mass = c(9, 11, 31, 33, 32, 33), BladeAR = c(1.56793743890518, 1.48101265822785, 1.36772046589018, 1.4803324099723, 3.46753246753247, 1.50310559006211), Subirrigation = c(0, 0, 0, 0, 0, 0), Genotype = c(1, 1, 1, 1, 1, 1), Location = c(0, 0, 0, 0, 0, 0)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame")) # 按Plant分组求和叶片总质量 plant_total_mass <- df %>% group_by(Plant) %>% summarise(total_leaf_mass = sum(Leaf.Mass, na.rm = TRUE))
group_by用于指定分组字段,summarise对每个分组执行汇总计算,na.rm = TRUE参数可以避免叶片重量存在缺失值时返回NA的问题。用你提供的示例数据运行后,会得到Plant=2的总叶片质量为84,Plant=3的总叶片质量为65。
方法2:使用基础R实现(无需安装额外包)
用内置aggregate函数即可完成分组求和:
plant_total_mass <- aggregate(Leaf.Mass ~ Plant, data = df, FUN = sum, na.rm = TRUE)
运行效果和tidyverse方案一致。
相关搜索关键词
如果需要查找更多相关解决方案,可以搜索以下关键词:
- R 分组求和
- R aggregate 函数用法
- R dplyr group_by summarise 汇总
- R 按列分组计算统计量
内容的提问来源于stack exchange,提问作者Joe Ballenger
相关产品推荐
相关产品推荐

