在 R 中使用带有条件的 sample()

Use sample() with conditions in R

我创建了一个数据集,用于将治疗随机分配给实验对象。个人将接受三次治疗。有 7 种治疗方法,我需要确保一个人在被随机分配时不会多次接受相同的治疗。有 35 个个体和 7 个处理,因此每个处理有 5 个重复。

数据:

set.seed(566)
treatments<-rep(c(2,4,8,16,32,64,100), each=5)
random_design<-data.frame(individual=c(1:35), trial1=sample(treatments), trial2=sample(treatments), trial3=sample(treatments))

如您所见,有些人在不同的试验中受到相同的待遇。 有没有办法对 sample() 施加条件,使个体 x 不能得到与之前试验相同的待遇?

你似乎想先给个体随机分配三种治疗方法,所以如果有 K 种治疗方法,而你想随机选择 3 种而不进行替换,那么对每个人都这样做,然后合并治疗效果。例如,使用您的号码,并使用 data.table,这是一个解决方案:

set.seed(566)
library(data.table)

exp_num = 7
#set up a data.table to hold treatment effects
treat_dt = data.table("experiment_num" = 1:exp_num, "treatment_effect" = c(2,4,8,16,32,64,100))

#now create a datatable of subjectsXtrials
subj_dt = data.table(expand.grid("id" = 1:35, "trial" = paste0("trial",1:3)))

#now randomly assign three experiments without replacement by id
subj_dt[, exp_assigned := sample(1:exp_num,3, replace = F), by = id]

#now merge in effects with treat_dt by experiment...
subj_dt = merge(subj_dt,treat_dt, by.x = "exp_assigned",by.y = "experiment_num", all.x = T, all.y = F)

#and youre done! option to get back a dataset where each id is a single row
alt_dt = dcast(subj_dt[,.(id,trial,treatment_effect)], id ~ trial, value.var = "treatment_effect")

然后 alt_dt

的输出如下所示
> head(alt_dt)
   id trial1 trial2 trial3
1:  1    100     32      8
2:  2    100     64     32
3:  3      4     16      2
4:  4    100     64      8
5:  5      8     16      4
6:  6     64    100      8