title: R - Tally for multiple factors in a column
body: <p>I have a sample data.frame, "events" which has multiple prey captures occurring on a single dive. Based on the Capture column, I have used the word "handling" to tally up the number of captures per dive. </p>
  
  <p>However, in some instances I have multiple prey types in a single dive. How can I work out the number of prey captures based on species (i.e. how many fish.a and how many fish.b caught in a single dive)? </p>
  
  <p>Any advice would be appreciated.</p>
  
  <pre><code>events &lt;- data.frame(Prey_present =c("fish.a", "fish.a","", "fish.b", 
  "fish.b","fish.b"),
  Capture = c("","","handling", "", "", "handling") ,
  Dive_id =c("dive.1", "dive.1","dive.1", "dive.1","dive.1", "dive.1"))
  
  temp&lt;- tapply(events$Capture, events$Dive_id, function(x) rle(x == 
  "handling"))
  ncaptures&lt;- data.frame(id = names(temp), 
  tally = unlist(lapply(temp, function(x) sum(x$values))))
  final&lt;-ncaptures[order(ncaptures$id),] 
  </code></pre>
  
  <p>My final output (which I will bind to my bigger data.frame) should be something like:</p>
  
  <pre><code>final &lt;- data.frame(fish.a =c(1),
  fish.b = c(1),
  Dive_id =c("dive.1"))                    
  </code></pre>