精華區beta R_Language 關於我們 聯絡資訊
大家好 最近在上程式語言的課 教授請我們跑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 請問這要怎麼撰寫呢? 想破頭還是想不出來 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.214.236.161 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1570199871.A.68F.html
andrew43: 給你個提示。產生一串亂數,取得大小順序,套在x的指標10/04 22:51
andrew43: ,這不就差不多是sample()的意思?10/04 22:51
andrew43: 至於怎麼取後放回,就上述過程多做幾次數但每次都只取10/04 22:54
andrew43: 出一個。提示到這裡。寫寫看吧。10/04 22:54
謝謝您,但是我還是寫不太出來,只好找教授求救了哈哈 ※ 編輯: siscom (49.217.236.224 臺灣), 10/05/2019 20:55:27
andrew43: 若x <- 1:5,那你先想想x[order(unif(5)]結果是什麼。 10/06 23:49
ksherry: 記得考慮若是抽出放回, 可能一組樣本被抽到多次 10/09 09:38
ksherry: 一個簡單的作法是, 假設資料有 10 筆, 則在均勻 [0,1] 中 10/09 09:39
ksherry: 將區間分成 10 等份, 例如若抽出一組數字為 0.33, 則抽第 10/09 09:40
ksherry: 4 筆樣本, 以此類推 10/09 09:40
andy19960407: https://www.codepile.net/pile/ZKEYnzKk 10/17 14:01
> -------------------------------------------------------------------------- < 作者: 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://www.ptt.cc/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