I want to use dplyr::summarise_at
on a collection of columns with a function object that uses an additional variable.
For example, consider the following data frame with two numeric variables and an indicator.
library(dplyr, warn.conflicts = FALSE)
t1 <- data.frame(lg = c(TRUE, FALSE, TRUE, FALSE),
x1 = 1:4,
x2 = 5:8)
Using dplyr::funs()
inside summarise_at
works:
t1 %>% summarise_at(c("x1", "x2"), funs(mean(. * lg)))
#> x1 x2
#> 1 1 3
However, I prefer passing a function
object to summarise_at
- instead of a call to dplyr::funs()
- so that R CMD Check
doesn't complain about the unknown variable .
.
Unfortunately, when I try to do this, summarise_at
can't find the indicator variable lg
.
t1 %>% summarise_at(c("x1", "x2"), function(x) mean(x * lg))
#> Error in summarise_impl(.data, dots): Evaluation error: object 'lg' not found.
Consequently, is there a way to pass a function object to summarise_at
with extra variables inside the function object in this way?