1

I have a dataframe that looks like the following:

unit_id  outcome
1        3
1        5
1        4
2        1
2        2
2        3

I know how to calculate the mean for each unit_id.

df <- df %>%
  group_by(unit_id) %>%
  summarise(mean = mean(outcome))

This yields:

unit_id  mean 
1        4
2        2

I am trying to figure out a way to get the mean for each unit_id and include that in the original dataframe. I would like the output to look like the following.

unit_id  outcome  mean
1        3        4
1        5        4
1        4        4
2        1        2
2        2        2
2        3        2
melbez
  • 960
  • 1
  • 13
  • 36

1 Answers1

1

We can use mutate instead of summarise

library(dplyr)
df <- df %>%
        group_by(unit_id) %>%
        mutate(mean = mean(outcome))
akrun
  • 874,273
  • 37
  • 540
  • 662