Search code examples
rstringobjecteval

Is there a R function that allows you to insert a variable inside a command?


For example: Imagine I have an object named "cors" which contains a string only ("Spain" for example). I would like then for "cors" to be replaced in the expression (1) below by "Spain", resulting in the expression (2):

#(1)
DF <- DF %>% filter(str_detect(Country, "Germany|cors", negate = TRUE))
#(2)
DF <- DF %>% filter(str_detect(Country, "Germany|Spain", negate = TRUE))

P.S: I know that in MATLAB this could be handled with the "eval()" command, though in R it apparently has a completely different applicability.


Solution

  • If we have an object, then place it outside the quotes and use paste/str_c to create the string

    library(dplyr)
    library(stringr)
    cors <- "Spain"
    pat <- str_c(c("Germany", cors),  collapse = "|")
    DF %>%
        filter(str_detect(Country, pat, negate = TRUE))
    

    Or another option is to string interpolate with glue (assuming cors object have only a single string element)

    DF %>%
        filter(str_detect(Country, glue::glue("Germany|{cors}"), negate = TRUE))
    

    Or this can be done in base R with grepl

    pat <- paste(c("Germany", cors), collapse = "|")
    subset(DF, !grepl(pat, Country))