R中同一列内的成对比较

ubof19bj  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(138)

我有一定的响应变量(生物量),我正在分析一系列的环境条件,从不同的论文检索。
示例数据集:
| 纸|生物量|条件|
| --------------|--------------|--------------|
| P1|10个|控制|
| P1|五|物种1|
| P1|0|种属1|
| P2|二|控制|
| P2|四|物种4|
| P2|六|物种4|
| P3|二|控制|
| P3|二|物种1|
| P3|八|物种2|
| P3|六|物种3|
| P3|七|物种4|
| P3|二|物种5|
| P4|三|控制|
| P4|1个|物种6|
对于每一篇论文,我想专门为对照划分每个物种的生物量结果。例如,对于P1(论文1),我想为对照划分(/)每个物种的生物量结果。
示例输出(我在这里使用了随机数字结果):
| 纸|比较|生物量结果|
| --------------|--------------|--------------|
| P1|对照与种属1|五|
| P2|对照与种属4|四|
| P3|对照与种属1|二|
| P3|对照与种属2|六|
| P3|对照与种属3|七|
| P3|对照与种属4|三|
| P3|对照与种属5|二|
| P4|对照与种属6|1个|
有什么建议吗?
我尝试使用tidyverse,但没有成功。

bogh5gae

bogh5gae1#

这可能会给予预期的结果。
首先sumSpecies,然后构造 Comparison 字符串,最后进行除法运算,filter得到最终结果。

library(dplyr)

df %>% 
  summarize(Biomass_sum = sum(Biomass), .by = c(Paper, Condition)) %>% 
  mutate(Comparison = paste("Control vs", Condition),
         Biomass_results = Biomass_sum / 
           Biomass_sum[Comparison == "Control vs Control"], .by = Paper) %>% 
  filter(Comparison != "Control vs Control") %>% 
  select(-c(Biomass_sum, Condition))
  Paper          Comparison Biomass_results
1    P1 Control vs Species1       0.5000000
2    P2 Control vs Species4       5.0000000
3    P3 Control vs Species1       1.0000000
4    P3 Control vs Species2       4.0000000
5    P3 Control vs Species3       3.0000000
6    P3 Control vs Species4       3.5000000
7    P3 Control vs Species5       1.0000000
8    P4 Control vs Species6       0.3333333
数据
df <- structure(list(Paper = c("P1", "P1", "P1", "P2", "P2", "P2", 
"P3", "P3", "P3", "P3", "P3", "P3", "P4", "P4"), Biomass = c(10L, 
5L, 0L, 2L, 4L, 6L, 2L, 2L, 8L, 6L, 7L, 2L, 3L, 1L), Condition = c("Control", 
"Species1", "Species1", "Control", "Species4", "Species4", "Control", 
"Species1", "Species2", "Species3", "Species4", "Species5", "Control", 
"Species6")), class = "data.frame", row.names = c(NA, -14L))

相关问题