title: Benford's Law in R
body: <p>I'm trying to implement Benford's Law in R. So far, everything works accordingly, except that if there are some first-digits with 0 occurrences, an exception is thrown:</p>
  
  <pre><code>Error in data.frame(digit = 1:9, actual.count = first_digit_counts, actual.fraction = first_digit_counts/nrow(fraudDetection),  : 
    arguments imply differing number of rows: 9, 5
  </code></pre>
  
  <p>This is because for my current data set, there are only first digits starting with 1, 2, 7, 8 and 9. How can I make it such that 3, 4, 5, 6 will have a count of 0 instead of not appearing at all in the table?</p>
  
  <p><strong>Current Data Set:</strong></p>
  
  <p><img src="https://i.stack.imgur.com/ikKu5.png" alt="Data Set"></p>
  
  <p>This is the part that is causing the exception to be thrown:</p>
  
  <pre><code>first_digit_counts &lt;- as.vector(table(fraudDetection$first.digit))
  </code></pre>
  
  <p>The current code in which this code fits in is as follows:</p>
  
  <pre><code># load the required packages
  require(reshape)
  require(stringr)
  require(plyr)
  require(ggplot2)
  require(scales)
  
  # load in data from CSV file
  fraudDetection &lt;- read.csv("Fraud Case in Arizona 1993.csv")
  names(fraudDetection)
  
  # take only the columns containing the counts and manipulate the data into a "long" format with only one value per row
  # let's try to compare the amount of the fraudulent transactions against the Benford's Law
  fraudDetection &lt;- melt(fraudDetection["Amount"])
  
  # add columns containing the first and last digits, extracted using regular expressions
  fraudDetection &lt;- ddply(fraudDetection, .(variable), transform, first.digit = str_extract(value, "[123456789]"), last.digit  = str_extract(value, "[[:digit:]]$"))
  
  # compare counts of each actual first digit against the counts predicted by Benford’s Law
  first_digit_counts &lt;- as.vector(table(fraudDetection$first.digit))
  first_digit_actual_vs_expected &lt;- data.frame(
  digit            = 1:9,
  actual.count     = first_digit_counts,    
  actual.fraction  = first_digit_counts / nrow(fraudDetection),
  benford.fraction = log10(1 + 1 / (1:9))
  )
  </code></pre>