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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With