title: How to calculate the number of occurrence of a given character in each row of a column of strings?
body: <p>I have a data.frame in which certain variables contain a text string.  I wish to count the number of occurrences of a given character in each individual string.</p>
  
  <p>Example:</p>
  
  <pre><code>q.data&lt;-data.frame(number=1:3, string=c("greatgreat", "magic", "not"))
  </code></pre>
  
  <p>I wish to create a new column for q.data with the number of occurence of "a" in string (ie. c(2,1,0)).</p>
  
  <p>The only convoluted approach I have managed is:</p>
  
  <pre><code>string.counter&lt;-function(strings, pattern){  
    counts&lt;-NULL
    for(i in 1:length(strings)){
      counts[i]&lt;-length(attr(gregexpr(pattern,strings[i])[[1]], "match.length")[attr(gregexpr(pattern,strings[i])[[1]], "match.length")&gt;0])
    }
  return(counts)
  }
  
  string.counter(strings=q.data$string, pattern="a")
  
   number     string number.of.a
  1      1 greatgreat           2
  2      2      magic           1
  3      3        not           0
  </code></pre>