title: R: classifying a text variable
body: <p>I have a data frame with a string variable representing diagnoses of diseases. I want to classify the diagnoses according to some rules:</p>
  
  <pre><code>rules &lt;- list(
    group1 = c('A012', 'A02', 'C30'),
    group2 = c('B01', 'B02')
  )
  </code></pre>
  
  <p>If the diagnosis field contains 'A01', 'A02' or 'A03' (including text that includes these patterns, e.g. 'A0199'), then the case should be put in group 1, and so on.</p>
  
  <p>My data looks like this:</p>
  
  <pre><code>dat &lt;- data.frame(
    ID = seq_len(10),
    diagnosis = c('A012', 'A01', 'B23', 'C43', 'B023', 'A99', 'A023', 'B012', 'B04', 'A07')
  )
  </code></pre>
  
  <p>The method I've used looks like this:</p>
  
  <pre><code># modify the rules so they work with grep    
  rules &lt;- lapply(rules, paste, collapse = '|')
  
  # create a function that classifies an individual diagnosis
  group &lt;- function(y) {
        a &lt;- sapply(rules, grepl, x = y)
        a &lt;- names(a)[a]
        return(if (length(a) == 0) NA else a)
      }
  
  # apply the function across the data frame
  dat$group &lt;- sapply(dat$diagnosis, group)
  </code></pre>
  
  <p>This seems to work, but my dataset is big and there are lots of rules, and it is extremely slow!</p>
  
  <p>Are there faster ways I could do this?</p>