Home > OS >  Dynamic variable names within an ifelse-function
Dynamic variable names within an ifelse-function

Time:02-19

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")

CodePudding user response:

As we are passing strings, converted to symbol and evaluate (!!) or use .data[[varname]] inplace of !!rlang::ensym(varname)

check_text <- function(.df, varname){
  #' Function checks for illegal characters in string variable
  .df %>% 
  mutate("check_{varname}" := 
     ifelse(!! rlang::ensym(varname) %in% c(".", "-", "--", "---", "???", "?"), 
       "wrong", "right"))  
}

-output

> dat %>% 
  check_text(varname = "txt1")
  duration Q1_1 Q1_2 Q1_3 Q1_4 Q2_1 Q2_2 Q2_3 Q2_4 Q2_5 age           txt1 check_txt1
1      198    1    2    4    1    0    0    0    1    0  20            ---      wrong
2     1839    2    2    2    2    0    0    1    0    0  30      asfasghjk      right
3     1922    3    3    1    5    1    1    1    1    1  10              .      wrong
4     1928    1    1    2    5    0    0    0    0    1  27         Subway      right
5    99999    4    5    4    5    1    1    1    1    1   1      Apple pie      right
6     1824    5    3    3    2    1    1    1    1    1  79 Another answer      right
  • Related