I want to make a custom function that I can apply to a range of variables in a data frame using the var1:var20
tidyselect syntax, but I'm running into an error. A basic example below:
library(dplyr)
mtcars
test_func <- function(start_var,end_var) {
mutate(across(start_var:end_var, ~ifelse(.x!=0,.x 1,.x)))
}
mtcars %>% test_func(mpg,hp)
The intended result (without using the function) is:
mtcars %>%
mutate(across(mpg:hp, ~ifelse(.x!=0,.x 1,.x)))
Using the function results in the following error message:
error in test_func(., mpg, hp) : unused argument (hp)
CodePudding user response:
Here's a potential solution:
library(dplyr)
test_func <- function(data, start_var, end_var) {
data %>%
mutate(across({{start_var}}:{{end_var}}, ~ifelse(.x!=0,.x 1000,.x)))
}
mtcars %>%
test_func(mpg, hp)
I changed your "else" arg to 1000 to highlight the change:
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 1021.0 1006 1160 1110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 1021.0 1006 1160 1110 3.90 2.875 17.02 0 1 4 4
Datsun 710 1022.8 1004 1108 1093 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 1021.4 1006 1258 1110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 1018.7 1008 1360 1175 3.15 3.440 17.02 0 0 3 2
More info about why this works can be found here
CodePudding user response:
You can make the following adjustments to your function to get it to work:
test_func <- function(data, start_var, end_var) { # add data source to the function
data %>% mutate(across({{start_var}}:{{end_var}}, ~ifelse(.x!=0,.x 1,.x))) # add {{}}
}
test_func(mtcars, mpg, hp)