Examples for 'dplyr::with_groups'


Perform an operation with temporary groups

Aliases: with_groups

Keywords:

### ** Examples

df <- tibble(g = c(1, 1, 2, 2, 3), x = runif(5))
df %>%
  with_groups(g, mutate, x_mean = mean(x))
# A tibble: 5 × 3
      g     x x_mean
  <dbl> <dbl>  <dbl>
1     1 0.149  0.441
2     1 0.733  0.441
3     2 0.983  0.813
4     2 0.642  0.813
5     3 0.400  0.400
df %>%
  with_groups(g, ~ mutate(.x, x1 = first(x)))
# A tibble: 5 × 3
      g     x    x1
  <dbl> <dbl> <dbl>
1     1 0.149 0.149
2     1 0.733 0.149
3     2 0.983 0.983
4     2 0.642 0.983
5     3 0.400 0.400
df %>%
  group_by(g) %>%
  with_groups(NULL, mutate, x_mean = mean(x))
# A tibble: 5 × 3
# Groups:   g [3]
      g     x x_mean
  <dbl> <dbl>  <dbl>
1     1 0.149  0.582
2     1 0.733  0.582
3     2 0.983  0.582
4     2 0.642  0.582
5     3 0.400  0.582
# NB: grouping can't be restored if you remove the grouping variables
df %>%
  group_by(g) %>%
  with_groups(NULL, mutate, g = NULL)
# A tibble: 5 × 1
      x
  <dbl>
1 0.149
2 0.733
3 0.983
4 0.642
5 0.400

[Package dplyr version 1.0.9 Index]