How to adjust mean values in summarize + across

Viewed 47

So basically I would like the equivalent of

mean(data$Column1, na.rm = TRUE) 

for the code below

Data<- Spread_sheet %>%
  group_by(Team) %>% 
  summarise(across(
    .cols = everything(),
    .fns = list(mean = mean), #mean(na.rm = TRUE) does not work
    .names = "{.fn} {.col}"
  )) 

Thanks!

1 Answers

You need to provide a function (!) to .fns where na.rm = TRUE is set. There are plenty of possibilities:

library(dplyr)

### 1 Function
my_mean <- function(..., na.rm = TRUE) mean(..., na.rm = na.rm)

mtcars %>% 
   group_by(am) %>%
   summarise(across(where(is.numeric), 
                    .fns = list(mean = my_mean)))

### 2 Lambda Function
mtcars %>%
   group_by(am) %>%
   summarise(across(where(is.numeric), 
                    .fns = list(mean = \(x) mean(x, na.rm = TRUE))))

### 3 Dplyr Function Style
mtcars %>%
   group_by(am) %>%
   summarise(across(where(is.numeric), 
                    .fns = list(mean = ~ mean(.x, na.rm = TRUE))))  

### 4 Using library `functional`
library(functional)
mtcars %>%
   group_by(am) %>%
   summarise(across(where(is.numeric), 
                    .fns = list(mean = Curry(mean, na.rm = TRUE)))) 
Related