Q:

Partial String Match in R Data Table

I am trying to match a string (or list of strings) from an R Shiny drop-down menu (multiple values selected) with data in a specific column of a data-table.
Details:

var_to_plot() is the list of strings (or single string if only one value is selected) which is selected on the dropdown menu in the R Shiny UI. It returns e.g. Var1
The data in the rows in the df$Relevant_Column that I want it to match looks like e.g:
Test1_Var1, Test2_Var1, Test2_Var2
I want to filter on both Var1 and Var2.
Selecting only 1 works when using Grepl, in code below, but not two, as I get the warning: "Warning in grep(var_to_plot(), df$Relevant_Column) :
argument 'pattern' has length > 1 and only the first element will be used"
I.e. it only filters on the first string in the list, not all of them.
So I tried using sqldf, but with no success as seen below.

I have  tried the following:

Using Grepl (returns warning):
df[grepl(var_to_plot(), df$Relevant_Column), ]
Using SQLDF (returns empty DF as for some reason it wont match from the var_to_plot())
df = sqldf("SELECT * FROM df WHERE Relevant_Column LIKE '%var_to_plot()%'")

A:

You'll likely want to concatenate the search terms into a valid regex, by separating them with a vertical bar.
df <- data.frame(
  rowid = 1:4,
  Relevant_Column = c("Test1_Var1", "Test2_Var1", "Test2_Var2", "Text3_Var3")
)

var_to_plot <- c("Var1", "Var2")

## Base R.
df[grepl(paste(var_to_plot, collapse = "|"), df$Relevant_Column), ]

## Tidyverse.
library("stringr")
library("dplyr")
filter(df, str_detect(Relevant_Column, str_c(var_to_plot, collapse = "|")))

## data.table
library("data.table")
DT <- as.data.table(df)
DT[grepl(paste(var_to_plot, collapse = "|"), Relevant_Column)]

