Search code examples
rdplyrcustom-function

Use a custom function in dplyr summarise(across())


This works as intended:

library(dplyr)

df <- data.frame(minutes = c(89,90,91),
             var1 = c(89, 90, 91),
             var2 = c(50, 100, 150))
df %>% 
  summarise(across(c(var1, var2), list(p90 = ~ .x / minutes * 90)))

However, when I try to turn it into a function. This does not work.

p90 <- function(df, ..., minutes = minutes){
  
  p90.fn <- list(p90 = ~ .x / minutes * 90)
  
  df %>% 
    summarise(across(vars(...), p90.fn))
  
}

df %>% p90(var1,var2)

All the answers on here point me to needing a {{}} somewhere but I'm at a lost. Thanks!


Solution

  • Just change the vars to c

    p90 <- function(df, ..., minutes = minutes){
      
       p90.fn <- list(p90 = ~ .x / minutes * 90)
      
       df %>% 
         summarise(across(c(...), p90.fn))
      
     }
    

    -testing

    library(dplyr)
    df %>%
        p90(var1,var2)
     var1_p90 var2_p90
    1       90  50.5618
    2       90 100.0000
    3       90 148.3516