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

在R中实现分组内Control与各物种Biomass的比值计算

解决方案:按文献分组计算生物量相对值

示例数据集

先构造一个和需求匹配的示例数据,方便验证代码:

library(tidyverse)

# 构造示例数据
df <- tibble(
  Paper = c("Paper1", "Paper1", "Paper1", "Paper2", "Paper2", "Paper2"),
  Biomass = c(10, 15, 8, 20, 25, 18),
  Condition = c("Control", "SpeciesA", "SpeciesB", "Control", "SpeciesC", "SpeciesD")
)

核心代码实现

用dplyr的分组+突变操作就能完成需求,关键是在每个分组内提取对照组的生物量值:

result_df <- df %>%
  group_by(Paper) %>%
  mutate(Relative_Biomass = Biomass / filter(., Condition == "Control") %>% pull(Biomass)) %>%
  ungroup()

代码逻辑说明

  • group_by(Paper):按文献分组,确保后续操作都在单篇文献的范围内执行
  • mutate(Relative_Biomass = ...):新增一列存储相对生物量
    • filter(., Condition == "Control") %>% pull(Biomass):在当前分组里筛选出Control行,提取对应的Biomass值(每组只有一个Control的话,这个值就是唯一的对照值)
    • 用当前行的Biomass除以该组的对照值,得到相对值

结果展示

运行后result_df的输出如下:

# A tibble: 6 × 4
  Paper  Biomass Condition Relative_Biomass
  <chr>    <dbl> <chr>                <dbl>
1 Paper1      10 Control                1  
2 Paper1      15 SpeciesA               1.5
3 Paper1       8 SpeciesB               0.8
4 Paper2      20 Control                1  
5 Paper2      25 SpeciesC               1.25
6 Paper2      18 SpeciesD               0.9

如果你的数据里某篇文献有多个Control重复值,可以用mean(filter(., Condition == "Control")$Biomass)取均值作为对照基准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:02:15