! Grep in R - Finding Items That Do Not Match [Duplicate]

I want to find rows in a dataframe that do not match a pattern.

 Key = c(1,2,3,4,5)
 Code = c("X348","I605","B777","I609","F123")
 df1 <- data.frame(Key, Code)

I can find items beginning with I60 using:

 df2 <- subset (df1, grepl("^I60", df1$Code))

But I want to be able to find all the other rows (that is, those NOT beginning with I60). The invert argument does not work with grepl. grep on its own does not find all rows, nor can it pass the results to the subset command. Grateful for help.

4

You could use the [ operator and do

df1[!grepl("I60", Code),]

(Suggested clarification from @Hugh:) Another way would be

df1[!grepl("I60",df1$Code),]

Here is the reference manual on array indexing, which is done with [:

3

Also, you can try this:

 Key = c(1,2,3,4,5)
Code = c("X348","I605","B777","I609","F123")
df1 <- data.frame(Key, Code)
toRemove<-grep("^I60", df1$Code)
df2 <- df1[-toRemove,]
2
Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest