跳轉到內容

統計分析:使用 R 入門/R/隨機抽樣

來自華夏公益教科書,開放的書本,開放的世界

隨機抽樣

[編輯 | 編輯原始碼]
從幫助頁面中,我們已經看到 sample 函式可以接受許多不同的引數。x 必須是一個包含專案的向量,size 必須是一個數字。由於 1:6 給出從 1 到 6 的數字向量,我們可以設定 x=1:6 和 size=5。這裡有 5 個示例(注意,前 4 個是等效的,雖然實際結果會因抽樣時的隨機效應而有所不同[1])。
###The next 4 lines are equivalent, 5 numbers are selected from a list of 1..6
sample(x=1:6, size=5, replace=FALSE) #when sampling WITHOUT replacement, each number only appears once
sample(replace=FALSE, size=5, x=1:6) #you can change the order of the arguments
sample(x=1:6, size=5)                #the same, because replace=FALSE by default
sample(1:6, 5)        #we don't need x= and size= if arguments are in the same order as in the help file
### The next line is a different model
sample(1:6, 5, TRUE)                 #sampling WITH replacement (the same number can appear twice)
###The next 4 lines are equivalent, 5 numbers are selected from a list of 1..6
sample(x=1:6, size=5, replace=FALSE) #when sampling WITHOUT replacement, each number only appears once
[1] 1 5 4 3 6
sample(replace=FALSE, size=5, x=1:6) #you can change the order of the arguments
[1] 5 6 4 2 1
sample(x=1:6, size=5)                #the same, because replace=FALSE by default
[1] 2 3 4 6 5
sample(1:6, 5)        #we don't need x= and size= if arguments are in the same order as in the help file
[1] 1 6 3 5 4
### Now simulate a different model
sample(1:6, 5, TRUE)                 #sampling WITH replacement (the same number can appear twice)
[1] 3 6 2 1 3
如上所述,我們的“公平骰子”模型是帶有放回的抽樣:同一個數字可以出現兩次(並且實際上在我們的資料中確實出現了)。因此,我們在 R 中的模擬模型很簡單:
sample(1:6, 5, TRUE) 


參考文獻

[編輯 | 編輯原始碼]
  1. 在每章之前呼叫 set.seed(1) 以獲得完全相同的結果
華夏公益教科書