Sample code:
library(tidyverse)
iris <- iris
test_tidyeval <- function(data, col_name, col_name_2, column1) {
mutate(
data,
{{col_name}} := case_when(Species == "setosa" ~ column1 + Sepal.Width + Petal.Length,
TRUE ~ column1),
{{col_name_2}} := case_when(Species == "setosa" ~ {{col_name}} + 100,
TRUE ~ {{col_name}} + 500))
}
iris %>% test_tidyeval("new_column_test", "new_column_test_2", Sepal.Length)
I'm sure this is a tidyeval/nse issue which I can never get my head around.
What I basically want is for new_column_test
to be created where if the row Species == "setosa" then for this to be the sum of Sepal.Length, which we're passing to column1
in the user-defined function, Sepal.Width and Petal.length, else just return the value from Sepal.Length, then for new_column_test_2
to add 100 to new_column_test
with the same logical condition used previously and 500 to non setosa species.
I can seem to manipulate the LHS of case_when okay but I'm stuck on the RHS statements.