DOS
DOS

Reputation: 75

How to perform multiple column products in R using `mutate` and `across`?

I have two data frames, named dft0 and dft1, each having variables that are related to each other. Specifically, for each column in dft0 named v, there is a corresponding column in dft1 named b_v. (Besides these variables, the two data frames have a variable in common that identifies observations and which is named id.) For each pair of variables v and b_v, I would like to obtain the product v * b_v and store it in a column named p_v using dplyr's mutate and across function. I tried it, but it seems that I need to do some adjustment to my code in order to make it work.

To illustrate the problem that I am having, consider the following two data frames below:

library(dplyr)

dft0 <- data.frame(id = 101:103, x   = 1:3,   y   = 4:6,   z   = 7:9)
dft1 <- data.frame(id = 101:103, b_x = 10:12, b_y = 13:15, b_z = 16:18)

I have (unssuccessfully) tried to perform the following step:

vs   <- c('x', 'y', 'z')
dfts <- full_join(dft0, dft1, by = c('id')) %>%
  mutate(., across(vs, .fn = ~ .x * get(paste0('b_', .x)), .names = 'p_{.col}'))

The execution of the above code returned the following error message:

Error in `mutate_cols()`:
! Problem with `mutate()` input `..1`.
i `..1 = across(...)`.
x first argument has length > 1
Caused by error in `get()`:
! first argument has length > 1
Run `rlang::last_error()` to see where the error occurred.

Is there something that can be done to make the mutate part of the above code work?

Upvotes: 1

Views: 30

Answers (0)

Related Questions