-3

I have the following data:

ID       Value
1         3
1         5

How can I compute the mean by ID, and put the mean in the data frame as a new variable such that it is repeated for the same ID. The result should look like this:

ID       Value   Mean
1         3       4
1         5       4

Thanks.

finstats
  • 1,349
  • 4
  • 19
  • 31

2 Answers2

1

You can use the 'ave' function from 'base' R:

df=data.frame(ID=c(1,1), value=c(3,5))
df['mean'] <- ave(df$value, df$ID, FUN=mean)

> df
###   ID value mean
### 1  1     3    4
### 2  1     5    4
agenis
  • 8,069
  • 5
  • 53
  • 102
1

You can compute the mean by group using ave(). Assuming your data frame is called df, you can do the following:

df$Mean <- with(df, ave(Value, ID, FUN=mean))

This adds Mean as another column in your data frame.

Alex A.
  • 5,466
  • 4
  • 26
  • 56