Search code examples
rtidyversetidyeval

use variable in str_detect's first argument


I want to use the str_detectfunction passing a variable as the first argument. Meaning this could theoretically look something like this.

# create the variable
var = names(mtcars)[1]
mtcars %>% 
  mutate(
    new_var = case_when(str_detect(var, "^2"), "two", "other")
  )

Now I'm not sure how to insert the variable var correctly into the str_detect function. I guess some tidy-eval is necessary, but I'm not sure....


Solution

  • using mtcars as an exmaple for string manipulation is not very helpful, so switching over to iris. Also, your case_when specification was wrong, so I'm using if_else for this example.

    You can use !!(sym(var))

    library(tidyverse)
    var <- "Species"
    iris %>% 
      mutate(
        new_var = if_else(str_detect(!!sym(var), "set"), "two", "other")
      )
    
      Sepal.Length Sepal.Width Petal.Length Petal.Width Species new_var
    1          5.1         3.5          1.4         0.2  setosa     two
    2          4.9         3.0          1.4         0.2  setosa     two
    3          4.7         3.2          1.3         0.2  setosa     two
    4          4.6         3.1          1.5         0.2  setosa     two
    5          5.0         3.6          1.4         0.2  setosa     two
    6          5.4         3.9          1.7         0.4  setosa     two