跳转到内容

统计分析:使用 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) 以获得完全相同的结果
华夏公益教科书