title: How to count number of unique values in a categorical variable, by groups of multiple columns
body: <p>I am having a terrible time figuring out this script. I am working with camera trap data, and have variables for camera name, species, and time of day species was captured on camera (day or night). I want to know for each camera, how many times each species occurred during the day. Ultimately I am looking for a variable, perc.day, of the percent of occurrences during the day for each species for each camera. perc.day would be # of &quot;day&quot; detections / all total detections for each species on each camera. I have been using dplyr and data.table.</p>
  <p>Here is a sample of what the data looks like:</p>
  <pre><code>camera &lt;- c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C')
  species &lt;- c('deer', 'deer', 'deer', 'coyote', 'deer', 'deer', 'deer', 'deer', 'coyote', 'coyote', 'coyote', 'bobcat')
  time_cat &lt;- c('day', 'day', 'night', 'day', 'night', 'day', 'day', 'day', 'night', 'day', 'night', 'night')
  
  data &lt;- data.frame(camera, species, time_cat)
  </code></pre>
  <p>And what I need it to look like:</p>
  <pre><code>camera &lt;- c('A', 'A', 'B', 'C', 'C', 'C')
  species &lt;- c('deer', 'coyote', 'deer', 'deer', 'coyote', 'bobcat')
  total.detections &lt;- c('3', '1', '3', '1', '3', '1')
  perc.day &lt;- c('0.667', '0', '0.667', '100', '0.333', '0')
  
  data.final &lt;- data.frame(camera, species, total.detections, perc.day)
  </code></pre>
  <p>This code works up to the detections variable, but at a loss for how to get the perc.day variable</p>
  <pre><code>data.final &lt;- 
    data %&gt;%
    group_by(camera, species) %&gt;%
    summarize(total.detections = n())
  </code></pre>
  <p>Thank you for any help or advice.</p>