! grep in R - search for items that do not match

I want to find rows in a data frame that do not match the pattern.

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

I can find elements starting with I60 using:

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

But I want to be able to find all the other lines (that is, those that do not start with I60). The inverse argument does not work with grepl. grep alone does not find all rows and cannot pass results to a subset command. Thanks for the help.

+4
source share
2 answers

You can use the operator [and do

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

(Suggested explanation by @Hugh :) Another way:

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

Here is a reference guide for indexing an array, which is done with [:

http://cran.r-project.org/doc/manuals/R-intro.html#Array-indexing

+5

, :

 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

All Articles