0

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....

Lenn
  • 1,283
  • 7
  • 20
  • Is this inside a function you are writing? If so, that makes a difference. Could you put this in a broader context? Thanks. – Allan Cameron Jun 21 '22 at 09:27

1 Answers1

3

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
deschen
  • 10,012
  • 3
  • 27
  • 50
  • 1
    I recommend using the `.data` pronoun: `str_detect(.data[[var]])`. See https://rlang.r-lib.org/reference/topic-data-mask-programming.html#names-patterns – Lionel Henry Jun 21 '22 at 09:48