【原创】在SAS和R中实现区组随机

本文的主要目的是介绍如何在R与SAS中编程实现区组随机。

 

R

【原创】在SAS和R中实现区组随机
seed=20140124
blocksize = 20
N = 200
set.seed(seed)
block = rep(1:ceiling(N/blocksize), each = blocksize)
a1 = data.frame(block, rand=runif(length(block)), envelope= 1: length(block))
a2 = a1[order(a1$block,a1$rand),]
a2$group = rep(c("Group A", "Group B"),times = length(block)/2)
assign = a2[order(a2$envelope),]
head(assign,40)
【原创】在SAS和R中实现区组随机

输出结果:

【原创】在SAS和R中实现区组随机将该过程编译成函数,方便调用。

【原创】在SAS和R中实现区组随机
blockrand = function(seed,blocksize,N){  
    set.seed(seed) 
    block = rep(1:ceiling(N/blocksize), each = blocksize)
    a1 = data.frame(block, rand=runif(length(block)), envelope= 1: length(block)) 
    a2 = a1[order(a1$block,a1$rand),]
    a2$group = rep(c("Group A", "Group B"),times = length(block)/2)  
    assign = a2[order(a2$envelope),]  
    return(assign)
}
【原创】在SAS和R中实现区组随机

 

SAS

【原创】在SAS和R中实现区组随机
%let N = 200;
%let blocksize = 20;
%let seed = 20140124;
data blocks;
    call streaminit(&seed);
    do block = 1 to ceil(&N/&blocksize); 
        do item = 1 to &blocksize;
            if item le &blocksize/2 then group="Group A";
            else group="Group B";
            rand = rand(UNIFORM);
            output;
        end;
    end;
run;
proc sort data = blocks; by block rand;run;
proc print data = blocks (obs = 40) obs="Envelope";run;
【原创】在SAS和R中实现区组随机

输出结果:

【原创】在SAS和R中实现区组随机

【原创】在SAS和R中实现区组随机

将该过程封装成宏,方便调用。

【原创】在SAS和R中实现区组随机
%macro blockrand(N,blocksize,seed);
data blocks;
    call streaminit(&seed);
    do block = 1 to ceil(&N/&blocksize); 
        do item = 1 to &blocksize;
            if item le &blocksize/2 then group="Group A";
            else group="Group B";
            rand = rand(UNIFORM);
            output;
        end;
    end;
run;
proc sort data = blocks; by block rand;run;
%mend blockrand;
【原创】在SAS和R中实现区组随机

【原创】在SAS和R中实现区组随机

上一篇:教你用Photoshop制作绚丽格子特效的桌面壁纸


下一篇:photoshop鼠绘精细的玩雪人的儿童插画