lundi 19 mars 2018

Sample with constrain / Randomize with constrain

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 within 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))))

resulting in the following 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 example above the treatment c is two times at position 2. One treatment should not be two times at the same position. How can I achieve this?

More general: Is there an easy solution for sampling with constrain?




Aucun commentaire:

Enregistrer un commentaire