如何使用 Rstudio 在五个块中随机处理而不重复处理?

问题描述

果园实验中,有5个处理,5个区块。为了分析处理对树木和果实生长的影响,中间树行两侧的处理相同。如何随机化 R 中的处理,而不会使块的最后处理与下一个块的开始处理相同。例如,我已经使用 agricolae 包在他们的区块内随机化处理,但我得到了这样的随机化:

Block 1: 3 1 5 2 4 
Block 2: 2 3 4 5 1
Block 3: 2 5 1 4 3 
Block 4: 1 5 3 4 2
Block 5: 2 3 1 5 4

如您所见,块 4 以处理 2 结束,然后块 5 以 2 开始。如果可能,我想避免这种情况,但我不确定如何在 r 中进行。

实验的直观表示,其中处理未在其图中随机化:

The image is a visual representation of the experiment with the treatments not randomised within their plots

运行下面的解决方案,我遇到了新表不显示数字的问题。

Print screen of the command dput(head(data,20))

解决方法

想象一下你的数据是这样的:

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

注意 cumsumrle 允许我们返回块之间边界的索引。 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",times = 5))