Restricted Pattern / Randomized Restricted

I have the following data frame

 design <- read.table(text =
"block position
 1     1
 1     2
 1     3
 1     4
 2     1
 2     2
 2     3
 2     4", header = TRUE)

I want to randomly assign four treatments in one block. I could do this, for example, with the following code:

treatment <- letters[1:4]
set.seed(2)
design$treatment <- as.vector(replicate(2,sample(treatment, length(treatment))))

leading to the next data frame

> design
 block position treatment
 1        1         a
 1        2         c
 1        3         b
 1        4         d
 2        1         d
 2        2         c
 2        3         a
 2        4         b

Problem: in the above example, processing c twice in position 2. One procedure should not be twice in the same position. How can I achieve this?

More general: Is there a simple constrained sampling solution?

+4
source share
2 answers

The following method should guarantee (1) random treatment and (2) non-identical treatments in the same position for different blocks.

  • letters[1:4] gtools::permutations. perm.

    # Calculate all permutations of letters[1:4]
    library(gtools);
    treatment <- letters[1:4];
    perm <- permutations(length(treatment), length(treatment), treatment);
    
  • treatment , .

    design$treatment <- "";
    
  • perm block. , perm (.. ), . block. .

    set.seed(2017);
    for (i in 1:length(unique(design$block))) {
        smpl <- perm[sample(nrow(perm), 1), ];
        design$treatment[seq(1 + 4 * (i - 1), 4 * i)] <- smpl;
        # Remove all permutations with duplicated letters
        j <- 1;
        while (j <= nrow(perm)) {
            if (any(perm[j, ] == smpl)) perm <- perm[-j, ] else j <- j + 1;
        }
    }
    design;
    #    block position treatment
    #1     1        1         d
    #2     1        2         c
    #3     1        3         a
    #4     1        4         b
    #5     2        1         b
    #6     2        2         a
    #7     2        3         d
    #8     2        4         c
    

set.seed(...), .

+4

Maurits Evers. 1000 .

n_treat <- 20

# make large design file
design <- data.frame(block = rep(1:4, each = n_treat), position = rep(1:n_treat, 4))

# Calculate some (not all) random permutations
treatment <- 1:n_treat
perm <- t(replicate(1000,sample(treatment, length(treatment), replace = F)))

# Create empty treatment vector
design$treatment <- ""

# loop through all blocks,
# randomly draw a permutation from perm,
# remove permutations with identiacal entries at the same position.
set.seed(2017);
for (i in 1:length(unique(design$block))) {
  smpl <- perm[sample(nrow(perm), 1), ];
  design$treatment[seq(1 + n_treat * (i - 1), n_treat * i)] <- smpl;
  # Remove all permutations with duplicated letters
  j <- 1;
  while (j <= nrow(perm)) {
    if (any(perm[j, ] == smpl)) perm <- perm[-j, ] else j <- j + 1;
  }
}
+1

Source: https://habr.com/ru/post/1695070/


All Articles