I've read the Programming with dplyr document and tried to write a simple function wrapping around the case_when()
function.
library(dplyr)
data_test <- data.frame(
a = rep(c("a", "b", "c"), each = 5),
b = rnorm(15)
)
fun_test <- function(df, var1, var2) {
var1 <- enquo(var1)
var2 <- enquo(var2)
df <- mutate(df,
c = case_when(
!!var1 == "a" ~ 1,
!!var1 == "b" ~ 2,
!!var1 == "c" ~ 3
),
d = case_when(
!!var2 > 0 ~ 1,
!!var2 < 0 ~ 0
))
df
}
fun_test(data_test, a, b)
I'm hoping the new columns c
and d
would be created based on the values in a
and b
, but instead they are just NA
and 0
. Any ideas why this is the case?
Cheers.