Search code examples
rdplyr

Is there a multiple-columns-as-input version of dplyr's "across" function?


I had to write a function today like this

data1 %>%
  summarise(
   ab1 = fn(a1, b1),
   ab2 = fn(a2, b2), 
   ab3 = fn(a3, b3) 
  )
# imagine if there are 100 of them

If fn was a single argument function I could've done

data1 %>%
  summarise(across(starts_with("a", fn)))

But unfortunately, my function needs two columns as inputs. Is there a way to do this without writing a new line for every set of arguments?


Solution

  • You may use map2* functions to pass two set of columns.

    library(dplyr)
    library(purrr)
    
    data1 %>%
      summarise(map2_df(pick(starts_with("a")), pick(starts_with("b")), fn))
    
    #  a1 a2 a3
    #1 21 57 93
    

    Using data from @ThomasIsCoding but a different function since your code uses summarise it means it will have a single row at the end.

    fn <- function(a, b) {
      sum(a, b)
    }