想象一下,您的数据如下所示:
head(data,10)
# Block TreeMiddleRow
#1 Block 1 Treatment 1
#2 Block 1 Treatment 2
#3 Block 1 Treatment 3
#4 Block 1 Treatment 4
#5 Block 1 Treatment 5
#6 Block 2 Treatment 1
#7 Block 2 Treatment 2
#8 Block 2 Treatment 3
#9 Block 2 Treatment 4
#10 Block 2 Treatment 5
您可以使用while
循环继续按组重新采样,直到没有一个块边界彼此相等:
treatments <- rep("Tretment",nrow(data))
while(any(treatments[head(cumsum(rle(data$Block)$lengths),-1)] == treatments[head(cumsum(rle(data$Block)$lengths),-1)+1])){
treatments <<- unname(unlist(tapply(data$TreeMiddleRow,
data$Block,
FUN = function(x) sample(x,size = 5, replace = FALSE))))
}
data$TreeMiddleRow <- treatments
head(data,10)
# Block TreeMiddleRow
#1 Block 1 Treatment 2
#2 Block 1 Treatment 3
#3 Block 1 Treatment 4
#4 Block 1 Treatment 5
#5 Block 1 Treatment 1
#6 Block 2 Treatment 2
#7 Block 2 Treatment 5
#8 Block 2 Treatment 3
#9 Block 2 Treatment 4
#10 Block 2 Treatment 1
请注意,cumsum
withrle
允许我们返回块之间边界的索引。head(x,-1)
删除最后一个,因为我们不关心它:
head(cumsum(rle(data$Block)$lengths),-1)
#[1] 5 10 15 20
样本数据:
data <- data.frame(Block = rep(paste("Block",1:5),each = 5),
TreeMiddleRow = rep(paste("Treatment",1:5),times = 5))