作者celestialgod (天)
看板R_Language
标题Re: 重复取样不放回(不使用sample)
时间Sun Oct 13 18:31:06 2019
※ 引述《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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 119.14.59.166 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1570962668.A.FA0.html
※ 编辑: celestialgod (119.14.59.166 台湾), 10/13/2019 18:33:29
※ 编辑: celestialgod (119.14.59.166 台湾), 10/13/2019 18:34:14
※ 编辑: celestialgod (119.14.59.166 台湾), 10/13/2019 18:34:46