I have some problems writing a function that takes a dataframe and a variable name as arguments. Then the specified variable in the dataframe should be checked. How can I use the variable name within the ifelse-statement?
# Some test data
dat <- data.frame(duration = c(198, 1839, 1922, 1928, 99999, 1824),
Q1_1 = c(1, 2, 3, 1, 4, 5),
Q1_2 = c(2, 2, 3, 1, 5, 3),
Q1_3 = c(4, 2, 1, 2, 4, 3),
Q1_4 = c(1, 2, 5, 5, 5, 2),
Q2_1 = c(0, 0, 1, 0, 1, 1),
Q2_2 = c(0, 0, 1, 0, 1, 1),
Q2_3 = c(0, 1, 1, 0, 1, 1),
Q2_4 = c(1, 0, 1, 0, 1, 1),
Q2_5 = c(0, 0, 1, 1, 1, 1),
age = c(20, 30, 10, 27, 1, 79),
txt1 = c("---", "asfasghjk", ".", "Subway", "Apple pie", "Another answer")
)
# Checker function
check_text <- function(.df, varname){
#' Function checks for illegal characters in string variable
.df %>%
mutate("check_{varname}" := ifelse({{varname}} %in% c(".", "-", "--", "---", "???", "?"), "wrong", "right")) #<- doesnt work
}
# Apply checker function to test data
dat %>% check_text(varname = "txt1")