1

Suppose I have

tibble(id = c(1,1,2,2), data = c(1:4))

i.e.

id data
1  1
1  2
2  3
2  4

I want to add a column with id-secific means, i.e. I want to get to

id data id_means
1  1    1.5
1  2    1.5
2  3    3.5
2  4    3.5

How can I do this?

stollenm
  • 348
  • 1
  • 2
  • 11

1 Answers1

1

We can use mutate after grouping by 'id'

df1 %>%
  group_by(id) %>% 
  mutate(id_means = mean(data))
# A tibble: 4 x 3
# Groups: id [2]
#     id  data id_means
#  <dbl> <int>    <dbl>
#1  1.00     1     1.50
#2  1.00     2     1.50
#3  2.00     3     3.50
#4  2.00     4     3.50

data

df1 <- tibble(id = c(1,1,2,2), data = c(1:4))
akrun
  • 874,273
  • 37
  • 540
  • 662