Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading