-1

For data preprocessing in a data project I need to transform some values based on a changing condition. I'd like to make a function that uses a boolean returning function named condition and a list of vars.

my_function <- function(data, condition, list_of_vars) {
  mutate(
    data,
    across(list_of_vars, ifelse(condition, a_value, alternative)
  )
}

It seems like it should have something to do with quosures and maybe the {{ vars }} operator, something along the lines of:

my_function <- function(data, condition, list_of_vars) {
  mutate(
    data,
    across({{ list_of_vars }}, ifelse(condition, a_value, alternative)
  )
}

How can I pass list of vars in which some change take place?

xihh
  • 169
  • 2
  • 12
  • 1
    Does this answer your question? [Using across function in dplyr](https://stackoverflow.com/questions/62755979/using-across-function-in-dplyr) – Limey Jun 25 '22 at 08:42
  • I think @Limey's proposed answer gets you almost all the way there. Instead of `everything()` you need `all_of(list_of_vars)`. And, depending on the `condition`, you will likely need to parse it. I provided an example in the answer below. – DaveArmstrong Jun 25 '22 at 14:31

1 Answers1

0

Here's an example:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

data(mtcars)
my_function <- function(data, condition, list_of_vars) {
  mutate(
    data,
    across(all_of(list_of_vars), function(x)ifelse(eval(parse(text=condition)), 1, 0))
    )
    }

my_function(mtcars, condition="x > mean(x, na.rm=TRUE)",  c("hp", "qsec", "wt")) %>% 
  dplyr::select(hp, qsec, wt)
#>                     hp qsec wt
#> Mazda RX4            0    0  0
#> Mazda RX4 Wag        0    0  0
#> Datsun 710           0    1  0
#> Hornet 4 Drive       0    1  0
#> Hornet Sportabout    1    0  1
#> Valiant              0    1  1
#> Duster 360           1    0  1
#> Merc 240D            0    1  0
#> Merc 230             0    1  0
#> Merc 280             0    1  1
#> Merc 280C            0    1  1
#> Merc 450SE           1    0  1
#> Merc 450SL           1    0  1
#> Merc 450SLC          1    1  1
#> Cadillac Fleetwood   1    1  1
#> Lincoln Continental  1    0  1
#> Chrysler Imperial    1    0  1
#> Fiat 128             0    1  0
#> Honda Civic          0    1  0
#> Toyota Corolla       0    1  0
#> Toyota Corona        0    1  0
#> Dodge Challenger     1    0  1
#> AMC Javelin          1    0  1
#> Camaro Z28           1    0  1
#> Pontiac Firebird     1    0  1
#> Fiat X1-9            0    1  0
#> Porsche 914-2        0    0  0
#> Lotus Europa         0    0  0
#> Ford Pantera L       1    0  0
#> Ferrari Dino         1    0  0
#> Maserati Bora        1    0  1
#> Volvo 142E           0    1  0

Created on 2022-06-25 by the reprex package (v2.0.1)

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25