计算平均值并创建列

时间:2015-02-26 22:13:26

标签: r

我有两列(组和重量),我想计算平均组,然后用这个平均值减去每个单元格。我想在R中有一个函数,但我很难创建它。请帮忙。非常感谢

Group   weight  Diff
A       10     -2
A       14      2
B      12      -1
B      14       1
C      14       1
C      12      -1
D      12     -0.5
D      13      0.5

5 个答案:

答案 0 :(得分:3)

这是ave的工作。

> d <- data.frame(Group=rep(LETTERS[1:4], each=2),
+                 weight=c(10,14,12,14,14,12,12,13))
> d$Diff <- d$weight - ave(d$weight, d$Group)
> d
  Group weight Diff
1     A     10 -2.0
2     A     14  2.0
3     B     12 -1.0
4     B     14  1.0
5     C     14  1.0
6     C     12 -1.0
7     D     12 -0.5
8     D     13  0.5

答案 1 :(得分:2)

使用library(data.table)的替代方案:

d <- data.table(Group=rep(LETTERS[1:4], each=2), weight=c(10,14,12,14,14,12,12,13))
d[,Diff:=weight-mean(weight),by=Group]

答案 2 :(得分:0)

使用库(dplyr)

df1 %>%
  group_by(Group) %>%
  summarise( avg = mean(weight)) %>%
  left_join(df1, by="Group") %>%
  mutate( diff = weight - avg)

答案 3 :(得分:0)

library(dplyr)
df%>%   #df is your dataframe
group_by(Group)%>%
mutate(Diff=weight-mean(weight))

Source: local data frame [8 x 3]
Groups: Group

  Group weight Diff
1     A     10 -2.0
2     A     14  2.0
3     B     12 -1.0
4     B     14  1.0
5     C     14  1.0
6     C     12 -1.0
7     D     12 -0.5
8     D     13  0.5

答案 4 :(得分:0)

如果你想要一个普通的老函数,这应该做:

calcDiff <- function(data, group.col="Group", out.col="Diff") {
  lev <- levels(data[,group.col])
  avg.list = list()
  for( group in lev ) {
    avg.list[[group]] <- mean(data[data[,group.col]==group,"weight"])
  }
  avg.list <- unlist(avg.list)
  grp.averages <- avg.list[lev[data[,group.col]]]
  data[,out.col] = data[,'weight'] - grp.averages
  return(data)
}