Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the R equivalent of SQL's "LIKE '%searched_word%'"?

Tags:

sql

r

How would I check if a particular word is contained in the text of a field in my dataset using R.

In SQL, we can use the LIKE comparison operator. For example,

SELECT * FROM schools WHERE name LIKE '%Public School%'

If I had to do the same thing in R, how would I do that?

like image 718
user3422637 Avatar asked Jan 09 '23 15:01

user3422637


1 Answers

Given

schools <- data.frame(rank = 1:20, 
                 name = rep(c("X Public School", "Y Private School"), 10))

try this:

subset(schools, grepl("Public School", name))

or this:

schools[ grep("Public School", schools$name), ]

or this:

library(sqldf)
sqldf("SELECT * FROM schools WHERE name LIKE '%Public School%'")

or this:

library(data.table)
data.table(schools)[ grep("Public School", name) ]

or this:

library(dplyr)
schools %>% filter(grepl("Public School", name))
like image 200
G. Grothendieck Avatar answered Jan 12 '23 07:01

G. Grothendieck