R でベンフォードの法則を実装しようとしています。これまでのところ、最初の桁に 0 回の出現がある場合を除いて、すべてが適切に機能します。例外がスローされます。
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
これは、現在のデータ セットでは、1、2、7、8、および 9 で始まる最初の数字しかないためです。3、4、5、6 が表示されない代わりに、カウントが 0 になるようにするにはどうすればよいですかまったくテーブルにありますか?
現在のデータセット:
これは、例外がスローされる原因となっている部分です。
first_digit_counts <- as.vector(table(fraudDetection$first.digit))
このコードが適合する現在のコードは次のとおりです。
# load the required packages
require(reshape)
require(stringr)
require(plyr)
require(ggplot2)
require(scales)
# load in data from CSV file
fraudDetection <- 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 <- melt(fraudDetection["Amount"])
# add columns containing the first and last digits, extracted using regular expressions
fraudDetection <- 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 <- as.vector(table(fraudDetection$first.digit))
first_digit_actual_vs_expected <- data.frame(
digit = 1:9,
actual.count = first_digit_counts,
actual.fraction = first_digit_counts / nrow(fraudDetection),
benford.fraction = log10(1 + 1 / (1:9))
)