如何在R中的数据帧中减去配对样本

时间:2018-04-10 17:59:32

标签: r

我想相互减去配对样本,以获得CancerNormal之间的差异。在我的示例中,我将减去value中与Pairing相同的两行中的数字。我不确定要开始。

            value    Sample      Group  Pairing Dataset
Sample_100G 8.063495 Sample_100G Cancer     100 Wei et al.
Sample_100R 3.226365 Sample_100R Normal     100 Wei et al.
Sample_106G 4.551518 Sample_106G Cancer     106 Wei et al.
Sample_106R     0    Sample_106R Normal     106 Wei et al.
Sample_122G     0    Sample_122G Cancer     122 Wei et al.
Sample_122R 0.000000 Sample_122R Normal     122 Wei et al.

 Diff      Group  Pairing Dataaset
 8.06-3.22  Cancer     100 Wei et al.
 4.55-0     Cancer     106 Wei et al.
 0-0        Cancer     122 Wei et al.

2 个答案:

答案 0 :(得分:3)

library(tidyverse)
df %>% 
  select(-Sample) %>% 
  spread(Group, value) %>% 
  mutate(diff = Cancer - Normal)

#   Pairing    Dataset   Cancer   Normal     diff
# 1     100 Wei et al. 8.063495 3.226365 4.837130
# 2     106 Wei et al. 4.551518 0.000000 4.551518
# 3     122 Wei et al. 0.000000 0.000000 0.000000

答案 1 :(得分:1)

如果OP不太热衷于使用spread,则可以使用left_join作为解决方案:

library(dplyr)

left_join(filter(df, Group=="Cancer"), filter(df, Group=="Normal"), by="Pairing") %>%
  mutate(Diff = value.x - value.y) %>%
  select(Diff, Group = Group.x, Pairing, Dataset = Dataset.x )

#       Diff  Group Pairing    Dataset
# 1 4.837130 Cancer     100 Wei et al.
# 2 4.551518 Cancer     106 Wei et al.
# 3 0.000000 Cancer     122 Wei et al.