在 R 中绘制分层样本 [英] drawing a stratified sample in R

查看:46
本文介绍了在 R 中绘制分层样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设计我的分层样本

library(survey)
design <- svydesign(id=~1,strata=~Category,  data=billa, fpc=~fpc)

到目前为止一切都很好,但我现在如何以与简单采样相同的方式绘制样本?

So far so good, but how can I draw now a sample in the same way I was able for simple sampling?

set.seed(67359)  
samplerows <- sort(sample(x=1:N, size=n.pre$n))

推荐答案

如果您有分层设计,那么我相信您可以在每个层中随机抽样.这是使用 ddply 在每个层中进行比例采样的简短算法:

If you have a stratified design, then I believe you can sample randomly within each stratum. Here is a short algorithm to do proportional sampling in each stratum, using 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

这篇关于在 R 中绘制分层样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆