title: How to vectorize a function with multiple possible outputs in an R dataframe
body: <p>I am trying to apply a function to a <code>data.frame</code> column in R that detects whether or not specific string values exist. There are various string patterns that each constitute their own categorization. The function should create a new column that provides said classification (<code>dat$id_class</code>) based off the string in the <code>dat$id</code> column.</p>
  <p>I am relying on the <code>stringr</code> and <code>dplyr</code> packages to do this. Specifically, I'm using <code>dplyr::mutate</code> to apply the function.</p>
  <p>This code runs &amp; produces the exact results I'm looking for, but I'm looking for a faster solution (if one exists). This is obviously a small-scale example with a limited dataset, and this same approach on my very large dataset is taking much longer than desired.</p>
  <pre><code>library(stringi)
  library(dplyr)
  library(stringr)
  
  dat &lt;- data.frame(
              id = c(
                      sprintf(&quot;%s%s%s&quot;, stri_rand_strings(1000000, 5, '[A-Z]'),
                      stri_rand_strings(5, 4, '[0-9]'), stri_rand_strings(5, 1, '[A-Z]'))
              ))
  
  
  classify &lt;- function(x){
    if(any(stringr::str_detect(x,pattern = c('AA','BB')))){
      'class_1'
    } else if (any(stringr::str_detect(x,pattern = c('AB','BA')))){
      'class_2'
    } else {
      'class_3'
    }
  }
  
  dat &lt;- dat %&gt;% rowwise() %&gt;% mutate(id_class = classify(id))
  </code></pre>
  <p>There's a great chance this has already been answered, and that I'm just not looking in the right place, but it's worth a shot.</p>
  <p>Any assistance appreciated!</p>