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 !
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:
across
only allows us to work on one column at a time, values onlycur_column()
suffix=
), we know that var1
and var2
both have a .y
-complement[[
access on cur_data()
, which is generally the same as the original data coming into the pipe, in full context of grouping, arranging, and other columns recently added to the data within this or previous calls to mutate