通过SAS进行比例抽样

时间:2012-06-19 20:52:12

标签: sas sampling

我有600,000多个观察到的数据,我想要采样与其邮政编码成比例(数据中的邮政编码数量与其人口密度成正比)。数据中的关键变量是 ZIP CODE ID GROUP

我需要修复现有的SAS代码,这样当SAS选择ZIP代码时,它会选择 GROUP 中的所有记录。例如,如果选择 ID = 2 ,我也需要 ID = 1 ID = 3 。因此,我的所有邮政编码都在 GROUP = 1

ID  GROUP   ZIP
1   1   46227
2   1   46227
3   1   46227
4   2   47620
5   3   47433
6   3   47433
7   3   47433
8   4   46135
9   4   46135
10  5   46202
11  5   46202
12  5   46202
13  5   46202
14  6   46793
15  6   46793
16  7   46202
17  7   46202
18  7   46202
19  8   46409
20  8   46409
21  9   46030
22  9   46030
23  9   46030
24  10  46383
25  10  46383
26  10  46383

我有以下SAS代码,它会从数据中抽取1000个obs,但它只是随机选择邮政编码而不考虑 GROUP 变量。

proc freq data=sample;
    tables zip / out=outfreq noprint;
run;

data newfreq error; set outfreq;
    sampnum=(percent*1000)/100;
    _NSIZE_=round(sampnum, 1);
    sampnum=round(sampnum, .01);
    if _NSIZE_=0 then output error;
    if _NSIZE_=0 then delete;
    output newfreq;
run;

data newfreq2; set newfreq error;
    by zip;
    keep zip _NSIZE_;
run;

proc sort data=newfreq2;
    by zip;
run;

proc sort data=sample;
    by zip;
run;

/* proportional stratified sampling */
proc surveyselect data=sample seed=2020 out=sampout sampsize=newfreq2;
    strata zip;
    id id zip;
run;

我希望我能清楚地解释我的问题。如果没有,我会尝试澄清和/或详细说明不清楚的事情。

提前致谢。

3 个答案:

答案 0 :(得分:1)

这是一种似乎有效的尝试。

data test;
    input id group zip;
    cards;
1 1 46227
2 1 46227
3 1 46227
4 2 47620
5 3 47433
6 3 47433
7 3 47433
8 4 46135
9 4 46135
10 5 46202
11 5 46202
12 5 46202
13 5 46202
14 6 46793
15 6 46793
16 7 46202
17 7 46202
18 7 46202
19 8 46409
20 8 46409
21 9 46030
22 9 46030
23 9 46030
24 10 46383
25 10 46383
26 10 46383
;
run;

data test;
    set test;
    rand = ranuni(1200);
run;

proc sort data=test;
    by rand;
run;

/* 10 here is how many cases you want to sample initially */
data test;
    set test;
    if _n_ <= 10 then sample = 1;
    else sample = 0;
run;

proc sort data=test;
    by  group
        descending sample;
run;

data test;
    set test;
    by  group;
    retain keep;    

    if first.group and sample = 1 then keep = 1;
    if first.group and sample = 0 then keep = 0;

    if not first.group then keep = keep;

    drop    rand
            sample;

run;

proc sort data=test;
    by id;
run;

作为奖励,这里有一个R单线,可以得到相同的结果:

# 3 here is the number of cases being sampled
test[test$group %in% (test[sample(1:nrow(test),3),]$group),]

答案 1 :(得分:0)

不确定你的意思。您是否尝试对邮政编码进行采样(并返回每个邮政编码的所有视图)或者您是否需要按邮政编码分层的样本(意味着每个邮政编码为N obs)?您可能希望在SAS / STAT用户指南here中看到示例89.4。

答案 2 :(得分:0)

p上的'比例分配'这个例子。下面引用的文章中的第6条可能有所帮助:

proc surveyselect data=frame out=sampsizes_prop sampsize=400;
 strata cityside **/ alloc=prop**;
run;

文章:     http://analytics.ncsu.edu/sesug/2013/SD-01.pdf