Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

aggregate - Subtracting values group-wise by the average of each group in R

I am trying to subtract group means from each group's values.

For example:

> 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

I can find the group means:

> aggregate(x[,2],list(x$gene),mean)
  Group.1        x
1       A 31.26667
2       B 23.55000
3       C 20.50000

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

How can I do it in R?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A data.table method:

require(data.table)

setDT(x)[, `value-group.mean` := mean(value), by = gene][, `value-group.mean` := value - `value-group.mean`]

x
#   gene value value-group.mean
# 1:    A  32.3        1.0333333
# 2:    A  31.0       -0.2666667
# 3:    A  30.5       -0.7666667
# 4:    B  25.0        1.4500000
# 5:    B  22.1       -1.4500000
# 6:    C  20.5        0.0000000
# 7:    C  21.2        0.7000000
# 8:    C  19.8       -0.7000000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...