Calculate group mean, sum, or other summary stats. and assign column to original data
Solution 1:
You may do this in dplyr
using mutate
:
library(dplyr)
df %>%
group_by(group) %>%
mutate(grp.mean.values = mean(value))
...or use data.table
to assign the new column by reference (:=
):
library(data.table)
setDT(df)[ , grp.mean.values := mean(value), by = group]
Solution 2:
Have a look at the ave
function. Something like
df$grp.mean.values <- ave(df$value, df$group)
If you want to use ave
to calculate something else per group, you need to specify FUN = your-desired-function
, e.g. FUN = min
:
df$grp.min <- ave(df$value, df$group, FUN = min)