[R] Avoid duplication in dplyr::summarise

Lars Bishop lars52r at gmail.com
Sat Sep 9 12:30:03 CEST 2017


Dear group,

Is there a way I could avoid the sort of duplication illustrated below?
i.e., I have the same dplyr::summarise function on different group_by
arguments. So I'd like to create a single summarise function that could be
applied to both. My attempt below fails.

df <- data.frame(matrix(rnorm(40), 10, 4),
                 f1 = gl(3, 10, labels = letters[1:3]),
                 f2 = gl(3, 10, labels = letters[4:6]))


df %>%
  group_by(f1, f2) %>%
  summarise(x1m = mean(X1),
            x2m = mean(X2),
            x3m = mean(X3),
            x4m = mean(X4))

df %>%
  group_by(f1) %>%
  summarise(x1m = mean(X1),
            x2m = mean(X2),
            x3m = mean(X3),
            x4m = mean(X4))

# My fail attempt

s <- function() {
  dplyr::summarise(x1m = mean(X1),
                   x2m = mean(X2),
                   x3m = mean(X3),
                   x4m = mean(X4))
}

df %>%
  group_by(f1) %>% s
Error in s(.) : unused argument (.)

Regards,
Lars.

	[[alternative HTML version deleted]]



More information about the R-help mailing list