Home > Software design >  dplyr: Error in `summarise_at()`: ! `.funs` must be a one sided formula, a function, or a function n
dplyr: Error in `summarise_at()`: ! `.funs` must be a one sided formula, a function, or a function n

Time:08-16

I am working with the dplyr package, and am having trouble with the following error:

Error in `summarise_at()`:
! `.funs` must be a one sided formula, a function, or a function name.

I am trying to find the mean over each treatment group. Here is an example dataset to reproduce the error:

ex <- data.frame(treatment = c(1,2,3,1,2,3,1,2,3), percent = c(55,44,33,22,11,55,44,33,22))

Here is what I have tried:

# Change the treatments to a factor
ex$treatment <- as.factor(ex$treatment)

ex %>% 
  group_by(treatment) %>% 
  summarise_at(vars(percent), list(name=mean))

The error occurs here. How can I correct this?

Note: This can be done easily using the code below, but I have to keep renaming the columns and I don't want to do that:

df <- aggregate(x = ex$percent,
                by = list(ex$treatment),
                FUN = mean)

CodePudding user response:

_at/_all are deprecated in favor of across

library(dplyr)
ex %>% 
  group_by(treatment) %>%
  summarise(across(percent, list(name = ~ mean(.x))))

As there is only a single column, we don't even need across

ex %>%
   group_by(treatment) %>%
   summarise(percent_name = mean(percent), .groups = 'drop')

OP's code works in dplyr 1.0.9

ex %>% 
  group_by(treatment) %>% 
  summarise_at(vars(percent), list(name=mean))
# A tibble: 3 × 2
  treatment  name
  <fct>     <dbl>
1 1          40.3
2 2          29.3
3 3          36.7
  • Related