Regular Expressions and ID's in R

Viewed 55

Say I have an example of data like this:

ID      Text
23      Patient has a probable chance of diabetes
78      He had to go to the doctor today
92      He mentioned possible diabetes
83      Patient likely has diabetes
45      She told us about her family history

I want to find the texts where it says "probable" or "possible" diabetes, but I want to return the list of ID's and their matching text where those are found. In this case, I want to return a dataset of:

ID     Text
23      Patient has a probable chance of diabetes
92      He mentioned possible diabetes
3 Answers

Try:

library(dplyr)
library(stringr)

df  %>%  filter(str_detect(Text, "possible|probable"))

#> A tibble: 2 x 2
#>     ID Text                                     
#>  <dbl> <chr>                                    
#>1    23 Patient has a probable chance of diabetes
#>2    92 He mentioned possible diabetes   

data

library(tibble)

df <- tribble(
~ID, ~Text,
23, "Patient has a probable chance of diabetes",
78, "He had to go to the doctor today",
92, "He mentioned possible diabetes",
83, "Patient likely has diabetes",
45, "She told us about her family history")

You may try:

^.*?(?:probable|possible).*

Explanation of the above regex:

  • ^ - Represents start of the line.
  • .*? - Matches everything except new-line lazily zero or more times.
  • (?:probable|possible) - Represents a non-capturing group matching either the word probable or possible.
  • .* - Matches everything except new-line greedily zero or more times.

enter image description here

Regex Demo

With Base R:

df = read.table(text="ID      Text
23      'Patient has a probable chance of diabetes'
                78      'He had to go to the doctor today'
                92      'He mentioned possible diabetes'
                83      'Patient likely has diabetes'
                45      'She told us about her family history'", header = TRUE)

df[(grep('possible|probable', df$Text)), ]
#>   ID                                      Text
#> 1 23 Patient has a probable chance of diabetes
#> 3 92            He mentioned possible diabetes
Related