Re: 重複取樣不放回(不使用sample)

作者: celestialgod (天)   2019-10-13 18:31:06
※ 引述《siscom (妹控)》之銘言:
: 大家好
: 最近在上程式語言的課
: 教授請我們跑bootstrap
: 但不使用sample的function 而是自己寫function
: 條件為
: Create a function call my.sample with three arguments:
: x:the data to be resampled
: n:number of data points to sample
: Replacement:resample with replacement or not
: Only ‘runif’ ‘order’ and ‘if else’ statements are allowed
: 請問這要怎麼撰寫呢?
: 想破頭還是想不出來
my.sample <- function(x, n, replace = FALSE) {
if (!replace && length(x) < n)
stop("The size must be less than the size of x when replace is TRUE.")
if (replace) {
prob <- 0:length(x)/length(x)
return(x[findInterval(runif(n), prob)])
} else {
return(x[order(runif(length(x)))][1:n])
}
}
findInterval如果不能用就自己用迴圈做一個吧XD

Links booklink

Contact Us: admin [ a t ] ucptt.com