Using column-wise operations in dplyr to divide multiple column values by a specified row

Viewed 137

How can I use column-wise operations in dplyr to divide multiple column values by a specified row? This question has been answered several times for the case of individual columns, but I am trying to find a solution for multiple columns using dplyr's column-wise across function. (The only relevant answers that I could find use the superseded mutate_at function.)

Here's an example of what I'm trying to accomplish, using a toy dataset:

library(dplyr)

df_pre <- tribble(~name, ~q_1, ~q_2,
              "max", 5, 4,
              "a", 4, 2,
              "b", 3, 1)

I want to divide each value in each column prefixed q_ by the value in the row for which name = "max". I can do this individually for each column:

df_post <- df_pre %>% 
  mutate(q_1 = q_1 / q_1[name == "max"]) %>% 
  mutate(q_2 = q_2 / q_2[name == "max"])

But my attempt to do the same thing using a column-wise operation throws an error:

df_post <- df_pre %>% 
  mutate(across(starts_with("q_")), ~ .x / .x[name == "max"])
#> Error: Problem with `mutate()` input `..2`.
#> ℹ `..2 = ~.x/.x[name == "max"]`.
#> x `..2` must be a vector, not a `formula` object.

What am I doing wrong with the last line of code?

1 Answers

across should be closed after the .fns

library(dplyr)
df_pre %>% 
  mutate(across(starts_with("q_"), ~ .x / .x[name == "max"]))

-output

# A tibble: 3 x 3
  name    q_1   q_2
  <chr> <dbl> <dbl>
1 max     1    1   
2 a       0.8  0.5 
3 b       0.6  0.25

The usage of ?across is

across(.cols = everything(), .fns = NULL, ..., .names = NULL)

Related