rdplyr

How to create multiple columns with across?


I'd like to write the equivalent of this R code in a more synthetic way because in my real example I have a lot of var1, var2 columns.

I thought it would be possible with across?

library(dplyr)

price <- tribble(
  ~code, ~var1, ~var2,
  "a", 1, 8,
  "b", 4, 5
)

quant <- tribble(
  ~code, ~var1, ~var2,
  "a", 10, 90,
  "b", 12, 88
)

# what I want to do in a more synthetic way
tab3 <- data.frame(
  code = price$code,
  var1 = price$var1 * quant$var1,
  var2 = price$var2 * quant$var2
)

Many thanks in advance !


Solution

  • We can left-join and mutate across the known variables.

    library(dplyr)
    left_join(price, quant, by = "code", suffix = c("", ".y")) %>%
      mutate(across(c(var1, var2), ~ . * cur_data()[[paste0(cur_column(), ".y")]])) %>%
      select(-ends_with(".y"))
    # # A tibble: 2 × 3
    #   code   var1  var2
    #   <chr> <dbl> <dbl>
    # 1 a        10   720
    # 2 b        48   440
    

    Explanation: