通过 R 中每个组的平均值逐组减去值 [英] Subtracting values group-wise by the average of each group in R
本文介绍了通过 R 中每个组的平均值逐组减去值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从每个组的值中减去组均值.
I am trying to subtract group means from each group's values.
例如:
> x <- data.frame('gene' = c('A','A','A','B','B','C','C','C'),'value' = c(32.3,31,30.5,25,22.1,20.5,21.2,19.8))
> x
gene value
1 A 32.3
2 A 31.0
3 A 30.5
4 B 25.0
5 B 22.1
6 C 20.5
7 C 21.2
8 C 19.8
我能找到组的意思是:
> aggregate(x[,2],list(x$gene),mean)
Group.1 x
1 A 31.26667
2 B 23.55000
3 C 20.50000
如何用对应的组均值减去 x 中的值"?我想要的结果如下:
How do I subtract the "value" in x by the corresponding group mean? My desire result is as follow:
gene value-group.mean
1 A 1.03333
2 A -0.26667
3 A -0.76667
4 B 1.45
5 B -1.45
6 C 0
7 C 0.7
8 C -0.7
我如何在 R 中做到这一点?
How can I do it in R?
谢谢.
推荐答案
使用库dplyr
,你可以:
library(dplyr)
x %>%
group_by(gene) %>%
mutate_all(funs(.-mean(.)))
# A tibble: 8 x 2
# Groups: gene [3]
gene value
<fct> <dbl>
1 A 1.03
2 A -0.267
3 A -0.767
4 B 1.45
5 B -1.45
6 C 0
7 C 0.700
8 C -0.700
这篇关于通过 R 中每个组的平均值逐组减去值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文