jmich738
jmich738

Reputation: 1675

R - using LIKE operator with variable

I want to substitute a variable instead of a string in the %like% function from DescTools package. What I want to do with it after is to have a loop where the variable changes value and I get a different results.
I've tried a few ways but can't get it working.
Here is my sample code:

    library(DescTools)
    library(dplyr)
    x <- c(1,2,3,4,5,6)
    y <- c("a","b","c","a","a","a")
    df <- data.frame(x = x, y = y)
    df

Here is what I get if I seach for "a" in the x column. This is the desired output.

 df %>% filter(y %like% "%a%")

# desired output
> df %>% filter(y %like% "%a%")
  x y
1 1 a
2 4 a
3 5 a
4 6 a

Now I want to create a variable which will hold the value I want to search

   # create a variable which will take out the value I'm looking for
        let <- '"%a%"'

If I use that variable in place of the string, I get either no result or the wrong result.
Is there any way for me to use a variable insetead of a string?

#not working
df %>% filter(y %like% let)

> df %>% filter(y %like% let)
[1] x y
<0 rows> (or 0-length row.names)

#not working
df %>% filter(y %like% cat(let))

> df %>% filter(y %like% cat(let))
"%a%"  x y
1 1 a
2 2 b
3 3 c
4 4 a
5 5 a
6 6 a

Upvotes: 0

Views: 2164

Answers (1)

Kim
Kim

Reputation: 4308

Option 1: Evaluate the variable.

df %>% filter(y %like% eval(parse(text = let)))

Option 2: Take advantage of the filter_ function in dplyr.

df %>% filter_(paste0("y %like%", let))

Edit: actually, the comments are better answers because it's less convoluted---it was the quote level that was the problem.

Upvotes: 2

Related Questions