PokeC PokeC - 2 months ago 8
R Question

Aggregating in R per ID but keeping the ID repetitions

If I have the table

ID 1 1 1 2 2
N. 3 2 1 1 1


I want to get the same number of rows but with a new column that would be the mean of N per ID.

Ie

ID 1. 1 1 2 2
N. 3 2 1 1 1
Mean(N) 2 2 2 1 1


How to do that in R?

Answer

Yet another way:

df
  ID N
1  1 3
2  1 2
3  1 1
4  2 1
5  2 1

df$Mean <- rep(aggregate(N~ID, df, mean)[,2], table(df$ID))

df
  ID N Mean
1  1 3    2
2  1 2    2
3  1 1    2
4  2 1    1
5  2 1    1