如何按因子生成随机处理变量? [英] How to generate a random treatment variable by factor?

查看:60
本文介绍了如何按因子生成随机处理变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义

x <- data.frame(
     ID=letters[1:10],
     class = as.factor(c(rep(1,5),rep(2,5))),
     treat = rep(0,10))

s.t.

> x
   ID class treat
1   a     1     0
2   b     1     0
3   c     1     0
4   d     1     0
5   e     1     0
6   f     2     0
7   g     2     0
8   h     2     0
9   i     2     0
10  j     2     0

我有两个级别的治疗,1 &2. 我想为每个级别 s.t. 为每个班级分配一个单元.随机化后,我们会得到类似的结果:

I have a treatment with two levels, 1 & 2. I want to assign exactly one one unit per class to each level s.t. that, after randomization, we get something like:

> x
   ID class treat
1   a     1     0
2   b     1     0
3   c     1     1
4   d     1     0
5   e     1     2
6   f     2     0
7   g     2     0
8   h     2     0
9   i     2     2
10  j     2     1 

s.t.单位cj 获得1 级治疗,ei 获得2 级.

s.t. units c and j get level 1 of treatment and e and i level 2.

如何在 R 中生成处理向量?

How do I generate the treatment vector in R?

推荐答案

我假设您只想分配一个 1级处理和一个 2级处理每个班级.您可以使用 plyr 包中的 ddply 函数轻松完成:

I'll assume you just want to assign one level 1 treatment and one level 2 treatment in each class. You can use the ddply function from the plyr package to do it easily:

  set.seed(1)
  require(plyr)
> ddply(x, .(class), transform, 
        treat = replace(treat, sample(seq_along(treat),2), 1:2))

   ID class treat
1   a     1     0
2   b     1     1
3   c     1     0
4   d     1     0
5   e     1     2
6   f     2     0
7   g     2     0
8   h     2     1
9   i     2     2
10  j     2     0

解释一下:ddply 函数通过 class 变量分割数据帧,并且在每个数据帧内,它transforms" treat 列将 2 个随机选择的条目替换为 1 和 2.sample(...,2) 函数在 treat<中选择两个随机索引/code> 列.其他变体(例如,为每种处理类型分配 1 个以上)可以类似地进行.

To explain: the ddply function splits the data-frame by the class variable, and within each data-frame, it "transforms" the treat column by replacing 2 randomly chosen entries by 1 and 2. The sample(...,2) function picks two random indices in the treat column. Other variants (e.g. assign more than 1 of each treatment type) can be done similarly.

这篇关于如何按因子生成随机处理变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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