1

I am facing problem with using grep/grepl function in R. When I run grepl for multiple strings I do not know how to produce required result.

Text1 <- c("instance", "percentage", "n", 
          "instance percentage", "percentage instance")

ID <- c(1,2,3,4,5)

A <- c("A","B","C","D","E")

df <- data.frame(ID, Text1, A)

I want to find the string instance or percentage (or both and add another column "Result" and give 1 each time is found.

Results would look like this:

ID  Text1               A   Result
1   instance            A   1
2   percentage          B   1
3   n                   C   
4   instance percentage D   1
5   percentage instance E   1
Kalenji
  • 401
  • 2
  • 19
  • 42

1 Answers1

2

Use grepl to find presence of the required string and convert to integer.

df$Result <- as.integer(grepl("instance|percentage", df$Text1))

df
#  ID               Text1 A Result
#1  1            instance A      1
#2  2          percentage B      1
#3  3                   n C      0
#4  4 instance percentage D      1
#5  5 percentage instance E      1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks. Works like magic. If I want to add a condition that if A is contains to B that should be 0 in results? – Kalenji Jul 26 '19 at 08:56
  • @Kalenji Do you mean `df$Result <- as.integer(grepl("instance|percentage", df$Text1) & df$A != "B")` ? – Ronak Shah Jul 26 '19 at 09:00