1

I am searching through a column to find a pattern,

reg <- regexpr("pattern", Data$column1)
View(reg)

reg gives me some numbers as the following:

   [1]  43  15   2  11   
   [19]  22  28  20  11
   [37]  32  11  32  20

but I want reg to be 0 or 1 based on whether "pattern" has been found or not in Data$column1 .

When I used grepl,

 reg <- grepl("pattern", Data$column1)
    View(reg)

I only got TRUE values in reg. Not FALSE values. But I want both in the column. If it finds the pattern store TRUE in reg if not store FALSE. How can this be accomplished?

Gworld
  • 103
  • 10
  • @MrFlick I see no reason why that shouldn't be an answer. (Unless you just left a comment and then went searching for a duplicate) – Dason Feb 01 '15 at 23:36
  • @MrFlick but I also want the false value in the column. But reg only has true in the column. – Gworld Feb 01 '15 at 23:42
  • @Gworld Your comment doesn't make sense to me. How about you actually create a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Feb 01 '15 at 23:43
  • 1
    @Gworld That's not a reproducible example. It sounds like your pattern is matching every row. As you can see it works fine with: `x<-c("ant","dog","ant"); grepl("a",x)` – MrFlick Feb 01 '15 at 23:48

1 Answers1

3

Use grepl() instead which will return a TRUE/FALSE value. You can use as.numeric() to turn it to 0/1 if you want.

See the ?grep help page for all the different pattern finding functions.

MrFlick
  • 195,160
  • 17
  • 277
  • 295