设计我的分层样本
library(survey)
design <- svydesign(id=~1,strata=~Category, data=billa, fpc=~fpc)
到目前为止一切都很好,但是我现在如何以与简单采样相同的方式绘制样本?
set.seed(67359)
samplerows <- sort(sample(x=1:N, size=n.pre$n))
sampling
查看CRAN上的包(此处为 pdf),strata
尤其是功能。
这是一个了解您是否正在进行调查的好工具;CRAN 上的页面上有几个小插曲。
“官方统计”的任务视图包括与这些调查设计和抽样问题密切相关的几个主题 - 浏览它和推荐的软件包还可能会介绍您可以在工作中使用的其他工具。
如果您有分层设计,那么我相信您可以在每个层中随机抽样。这是一个在每个层中进行比例抽样的简短算法,使用ddply
:
library(plyr)
set.seed(1)
dat <- data.frame(
id = 1:100,
Category = sample(LETTERS[1:3], 100, replace=TRUE, prob=c(0.2, 0.3, 0.5))
)
sampleOne <- function(id, fraction=0.1){
sort(sample(id, round(length(id)*fraction)))
}
ddply(dat, .(Category), summarize, sampleID=sampleOne(id, fraction=0.2))
Category sampleID
1 A 21
2 A 29
3 A 72
4 B 13
5 B 20
6 B 42
7 B 58
8 B 82
9 B 100
10 C 1
11 C 11
12 C 14
13 C 33
14 C 38
15 C 40
16 C 63
17 C 64
18 C 71
19 C 92
您可以使用 绘制分层样本dplyr
。首先,我们按我们感兴趣的一个或多个列进行分组。在我们的示例中,每个 Species 有 3 条记录。
library(dplyr)
set.seed(1)
iris %>%
group_by (Species) %>%
sample_n(., 3)
输出:
Source: local data frame [9 x 5]
Groups: Species
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 4.3 3.0 1.1 0.1 setosa
2 5.7 3.8 1.7 0.3 setosa
3 5.2 3.5 1.5 0.2 setosa
4 5.7 3.0 4.2 1.2 versicolor
5 5.2 2.7 3.9 1.4 versicolor
6 5.0 2.3 3.3 1.0 versicolor
7 6.5 3.0 5.2 2.0 virginica
8 6.4 2.8 5.6 2.2 virginica
9 7.4 2.8 6.1 1.9 virginica
这是一种快速的方法,可以从 mtcars 数据框中对每个不同的“carb”值采样三个记录,而无需替换
# choose how many records to sample per unique 'carb' value
records.per.carb.value <- 3
# draw the sample
your.sample <-
mtcars[
unlist(
tapply(
1:nrow( mtcars ) ,
mtcars$carb ,
sample ,
records.per.carb.value
)
) , ]
# print the results to the screen
your.sample
请注意,该survey
软件包主要用于分析复杂的样本调查数据,而不是创建它。@Iterator 是正确的,您应该查看该sampling
包以获取更高级的方法来创建复杂的样本调查数据。:)