问题描述
我有一个数据框,其中包含列基因,它们所属的染色体区域,从中测量基因表达的细胞系以及该细胞系中基因的表达水平-基本上看起来像这样:
gene region cell_line expression
A X Joe 1
B X Joe 2
C Y Joe 2
D Z Joe 3
E Z Joe 0
A X Claire 2
B X Claire 1
C Y Claire 3
D Z Claire 3
E Z Claire 1
我要为每个细胞系计算不在给定区域内的所有基因的染色体区域的平均值,标准差等。例如,对于乔的X区域,我希望输出“ summarize()”行显示不在乔X中的所有基因(即乔的C,D,E基因)的表达平均值。
所以输出看起来像:
region cell_line mean_other standard_deviation_other
X Joe 1.67 some number
Y Joe 1.5 some number
Z Joe 1.67 some number
X Claire 2.33 some number
Y Claire 2.33 some number
Z Claire 2 some number
我的想法是执行以下操作,除了我不知道如何获取摘要以在给定时间“操作”的组之外操纵组。
df %>% group_by(region,cell_line) %>%
summarize(mean_other = mean(expression of cell lines not in this group),standard_deviation_other = var(expression of cell lines not in this group)
解决方法
我们可以使用新的dplyr::group_modify()
轻松地在组之间应用函数,该函数将每个组作为数据帧。然后,我们可以在原始数据帧上使用dplyr::anti_join()
并应用摘要中所需的任何内容。
使用mtcars
:
library(dplyr)
mtcars %>%
group_by(cyl) %>%
group_modify(~anti_join(mtcars,.) %>%
summarize(disp_m = mean(disp),disp_sd = sd(disp)))
#> # A tibble: 3 x 3
#> # Groups: cyl [3]
#> cyl disp_m disp_sd
#> <dbl> <dbl> <dbl>
#> 1 4 297. 101.
#> 2 6 244. 136.
#> 3 8 136. 50.7
并使用cyl == 4
检查第一组:
mtcars %>%
filter(cyl != 4) %>%
summarize(disp_m = mean(disp),disp_sd = sd(disp))
#> disp_m disp_sd
#> 1 296.5048 101.1434
在您的df
上,它应该看起来像这样:
df %>%
group_by(region,cell_line) %>%
group_modify(~anti_join(df,.) %>%
summarize(mean_other = mean(expression),sd_other = var(expression)))