colin
colin

Reputation: 2666

Generate randomized block schematic in R

I frequently design randomized block experiments, and my collaborators often enjoy schematics that visualize these designs. However, generating them is very time-consuming because I do this in powerpoint (I am ashamed). I would like to do this in R, but I don't really know how to get started. Below I have copied what one of these schematics looks like. What I'd really like to do is develop R code where the user can specify:

  1. Some number of treatments within block.
  2. A number of blocks.
  3. A vector of colors linked to the treatments.

I'd like the output to be the first panel of the below figure, without necessarily including the "Block 1", "Block 2", etc. labels. Though, this would be a bonus. Would love if the solution was in base R.

enter image description here

Upvotes: 0

Views: 307

Answers (1)

Seshadri
Seshadri

Reputation: 679

This might be what you want. I don't see why each block cannot simply be a row as shown in the picture below. If you need some fancy shapes, you need to specify the criteria for drawing that shape for the block.

library(tidyverse)
n_blocks <- 12
m_treatments <- 5

plot_sample_treatments <- function(n_blocks,m_treatments){
  df <- do.call("rbind",
                lapply(1:n_blocks, 
                       function(x) data.frame(
                         treatment = sample(1:m_treatments,m_treatments), 
                         block = paste0('Block ',x), 
                         sequence = (1:m_treatments))))
  df %>% ggplot(aes(x = sequence, y = block, fill = factor(treatment))) + 
        geom_tile(color = 'gray30') + 
        scale_x_discrete(expand = c(0,0))
}

plot_sample_treatments(12,5)

which gives the following:

enter image description here

Upvotes: 1

Related Questions