本文的主要目的是介绍如何在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)
输出结果:
将该过程编译成函数,方便调用。
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
%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;
输出结果:
将该过程封装成宏,方便调用。
%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;