Dplyr across multiple functions referencing other columns in dataframe

I'm trying to use multiple functions across multiple variables, like this:

I can get this to work:

df <- tibble(a = 2, b = 4, c = 8)

div_x_by_n <- list(
  div_2 = ~.x/2, 
  div_4 = ~.x/4)

df %>% mutate(across(everything(), div_x_by_n))

However, if I want to reference a column in the dataframe, I get an error:

div_x_by_ab <- list(
    div_a = ~.x/a, 
    div_b = ~.x/b)

df %>% mutate(across(everything(), div_x_by_ab))

Error: Problem with mutate() input ..1.
x object 'a' not found
i Input ..1 is across(everything(), div_x_by_a).

How can I reference columns from my dataframe within the list of functions that's passed to across?

I'm not well-versed enough in dplyr evaluation rules to know why your version doesn't work, but it looks like it works if you specify the functions directly in the mutate

df <- tibble(a = 2, b = 4, c = 8)

df %>%
  mutate(across(everything(), list(div_a = ~ .x / a,
                                   div_b = ~ .x / b)))
#> # A tibble: 1 x 9
#>       a     b     c a_div_a a_div_b b_div_a b_div_b c_div_a c_div_b
#>   <dbl> <dbl> <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
#> 1     2     4     8       1     0.5       2       1       4       2

Created on 2020-06-09 by the reprex package (v0.3.0)

1 Like

Thanks, that is interesting. Would be nice to get it working outside the mutate, but that at least provides the functionality!

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