次のコードを検討してください。
require(Hmisc)
num.boots <- 10
data <- rchisq(500, df = 5) #generate fake data
#create bins
binx <- cut(data, breaks = 10)
binx <- levels(binx)
binx <- sub("^.*\\,", "", binx)
binx <- as.numeric(substr(binx, 1, nchar(binx) - 1))
#pre-allocate a matrix to be filled with samples
output <- matrix(NA, nrow = num.boots, ncol = length(binx))
#do random sampling from the vector and calculate percent
# of values equal or smaller to the bin number (i)
for (i in 1:num.boots) {
walk.pair.sample <- sample(data, size = length(data), replace = TRUE)
data.cut <- cut2(x = walk.pair.sample, cuts = binx)
data.cut <- table(data.cut)/sum(table(data.cut))
output[i, ] <- data.cut
}
#do some plotting
plot(1:10, seq(0, max(output), length.out = nrow(output)), type = "n", xlab = "", ylab = "")
for (i in 1:nrow(output)) {
lines(1:10, output[i, 1:nrow(output)])
}
#mean values by columns
output.mean <- apply(output, 2, mean)
lines(output.mean, col="red", lwd = 3)
legend(x = 8, y = 0.25, legend = "mean", col = "red", lty = "solid", lwd = 3)
boot:boot()関数に、出力として長さn> 1のベクトルを持つ関数を提供できるかどうか疑問に思っていましたか?それは可能ですか?
これが私の弱い試みですが、私は何か間違ったことをしているに違いありません。
require(boot)
bootstrapDistances <- function(data, binx) {
data.cut <- cut2(x = data, cuts = binx)
data.cut <- table(data.cut)/sum(table(data.cut))
return(data.cut)
}
> x <- boot(data = data, statistic = bootstrapDistances, R = 100)
Error in cut.default(x, k2) : 'breaks' are not unique
Hmisc::cut2()
呼び出しで正しく機能しない理由はよくわかりませんが、ループboot()
で呼び出すと機能します(上記のコードを参照)。for()
私のbootstrapDistances()
関数のロジックはで実行可能boot()
ですか?どんなポインタでも大歓迎です。
。:編集:。
アニコは、インデックスを含めるように関数を変更することを提案しました。boot()のドキュメントを読んでいる間、これがどのように機能するかがわかりませんでした。これが、関数が機能しない理由を説明しています。アニコが提案した新機能は次のとおりです。
bootstrapDistances2 <- function(data, idx, binx) {
data.cut <- cut2(x = data[idx], cuts = binx)
data.cut <- table(data.cut)/sum(table(data.cut))
return(data.cut)
}
しかし、なんとかエラーが発生し、それを削除する方法をまだ検討中です。
> x <- boot(data = data, statistic = bootstrapDistances2, R = 100, binx = binx)
Error in t.star[r, ] <- statistic(data, i[r, ], ...) :
number of items to replace is not a multiple of replacement length
Rセッションを再開した後(別のバージョン2.10.1も試しました)、正常に動作しているようです。