across() - address columns outside the columns being operated on

Hi,

I would like to divide a set of columns by another set of columns, both to be found in my dataset.
For this, I use the mutate-across combo, but while I'm able to select my numerator (with "." (dot) , I am not able to select the denominator, which would be also columns in my dataset but outside the columns I am operating on (.cols).

df <- df %>%
mutate(across(.cols = starts_with("column_set1_prefix_"), .fns = ~. / column_set2, .names = "some_prefix_"))

I tried it by nesting a second "across()" function in the .fns argument of the first across() function, but that somehow made my saved data.frame extremely slow as something would have happened, what should now have happened.
I tried it like that:
df <- df %>%
mutate(across(
.cols = starts_with("column_set1_prefix_"),
".fns = ~ . / across(.cols = starts_with("column_set2_prefix_"), .fns. = identity)))

Could you help me, please, find out, how to select columns that are in my df, but outside the columns I'm operating on in my first across function call?

Kind regards,
Matt

I can't think of a way to do this with across(). I would use map2_df() from the purrr package. In thte code below, I break out each step, but the two select() steps could be placed within the map2_df().

library(purrr)
library(dplyr)

DF <- data.frame(A_1 = 1:4, A_2 = 2:5, B_1 = 3:6, B_2 = 4:7)
DF
#>   A_1 A_2 B_1 B_2
#> 1   1   2   3   4
#> 2   2   3   4   5
#> 3   3   4   5   6
#> 4   4   5   6   7
DF1 <- DF |> select(starts_with("A"))
DF2 <- DF |> select(starts_with("B"))
DF3 <- map2_df(DF1, DF2, `/`)
DF3
#> # A tibble: 4 × 2
#>     A_1   A_2
#>   <dbl> <dbl>
#> 1 0.333 0.5  
#> 2 0.5   0.6  
#> 3 0.6   0.667
#> 4 0.667 0.714

Created on 2023-04-05 with reprex v2.0.2

1 Like

Thank you, Sir. For the moment, I will go for that!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.