You can do this with dplyr::mutate_at
:
iris %>% group_by(Species) %>%
mutate_at(.vars = vars(Sepal.Length,Sepal.Width),
.funs = list(mean = ~mean))
We need the list(mean = ~mean)
bit, instead of just .funs = mean
to rename the columns, instead of writing over the original ones.
# A tibble: 150 x 7
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal.Length_mean Sepal.Width_mean
<dbl> <dbl> <dbl> <dbl> <fct> <dbl> <dbl>
1 5.1 3.5 1.4 0.2 setosa 5.01 3.43
2 4.9 3 1.4 0.2 setosa 5.01 3.43
3 4.7 3.2 1.3 0.2 setosa 5.01 3.43
4 4.6 3.1 1.5 0.2 setosa 5.01 3.43
5 5 3.6 1.4 0.2 setosa 5.01 3.43
6 5.4 3.9 1.7 0.4 setosa 5.01 3.43
7 4.6 3.4 1.4 0.3 setosa 5.01 3.43
8 5 3.4 1.5 0.2 setosa 5.01 3.43
9 4.4 2.9 1.4 0.2 setosa 5.01 3.43
10 4.9 3.1 1.5 0.1 setosa 5.01 3.43