Introduction

This package was developed to help prepare some samples to be send to a facility. It assumes that you have collected the samples and the information but you still need to do the experiment in several batches due to technical or practical limitations. The question that tries to answer is:

Which samples go with each batch?

Of all the possible combinations of samples, it looks for the combination which minimizes the differences between each subgroup according to the following rules:

  • If the variable is categorical it tires to randomize the variable across the subgroups.
  • If the variable is numeric it tries to distribute evenly following the original distribution of values.
  • If there are NA (not available values) it looks to distribute them randomly.

Even with this measures you might end up with some batch effect due to: - Confounding variables not provided for their randomization on the batches Sometimes due to being unknown, impossible to measure. - Lack of replicates(samples with the same conditions) If you can’t provide new replicates, aim to provide more technical replicates. Technical replicates mean reanalyzing the same sample twice or more, the more samples with technical replicates the more accurate your measures will be and easier to avoid or detect batch effects. - Processing If there is a change on the methodology, or you pause and resume later the sample collection there might be changes on the outcome due to external factors.

Previous work

Before building this package I would like to give credit to those that made also efforts in this direction:

The CRAN task View of Experimental Design includes many packages relevant for designing an experiment before collecting data, but none of them provides how to manage them once the samples are already collected.

Two packages allow to distribute the samples on batches:

  • The OSAT package handles categorical variables but not numeric data. It doesn’t work with our data.

  • The minDiff package reported in Stats.SE, handles both numeric and categorical data. But it can only optimize for two nominal criteria. It doesn’t work for our data.

  • The Omixer package handles both numeric and categorical data (converting categorical variables to numeric). But both the same way either Pearson’s Chi-squared Test if there are few samples or Kendall’s correlation. It does allow to protect some spots from being used.

If you are still designing the experiment and do not have collected any data DeclareDesign might be relevant for you.

Question in Bioinformatics.SE I made before developing the package.

Design of Experiment

Imagine you have some samples already collected and you want to distributed them in batches:

library("experDesign")
metadata <- expand.grid(height = seq(60, 80, 5), 
                        weight = seq(100, 300, 50),
                        sex = c("Male","Female"))
head(metadata, 15)
##    height weight  sex
## 1      60    100 Male
## 2      65    100 Male
## 3      70    100 Male
## 4      75    100 Male
## 5      80    100 Male
## 6      60    150 Male
## 7      65    150 Male
## 8      70    150 Male
## 9      75    150 Male
## 10     80    150 Male
## 11     60    200 Male
## 12     65    200 Male
## 13     70    200 Male
## 14     75    200 Male
## 15     80    200 Male

First we can check the data to see if there are any concerns regarding the categories:

check_data(metadata)
## [1] TRUE

There are none confounding variables in this artificial dataset (see the examples, and you’ll find some). However, if you block incorrectly and end up with a group in a single batch we will end up with batch effect.

In order to avoid this design() helps you assign each sample to a batch (in this case each batch has 24 samples at most). First we can explore the number of samples and the number of batches:

size_data <- nrow(metadata)
size_batch <- 24
(batches <- optimum_batches(size_data, size_batch))
## [1] 3
# So now the best number of samples for each batch is less than the available
(size <- optimum_subset(size_data, batches))
## [1] 17
# The distribution of samples per batch
sizes_batches(size_data, size, batches)
## [1] 17 17 16

Note that instead of using a whole batch and then leave a single sample on the third distributes all the samples in the three batches that will be needed.

Randomization

We can directly look for the distribution of the samples given our max number of samples per batch:

desi <- design(metadata, size_batch)
# It is a list but we can convert it to a vector with:
batch_names(desi)
##  [1] "SubSet2" "SubSet2" "SubSet1" "SubSet2" "SubSet1" "SubSet1" "SubSet1"
##  [8] "SubSet1" "SubSet3" "SubSet3" "SubSet3" "SubSet2" "SubSet1" "SubSet3"
## [15] "SubSet2" "SubSet3" "SubSet2" "SubSet2" "SubSet2" "SubSet2" "SubSet1"
## [22] "SubSet3" "SubSet3" "SubSet1" "SubSet2" "SubSet3" "SubSet3" "SubSet2"
## [29] "SubSet3" "SubSet2" "SubSet1" "SubSet1" "SubSet1" "SubSet1" "SubSet3"
## [36] "SubSet1" "SubSet1" "SubSet3" "SubSet3" "SubSet2" "SubSet2" "SubSet2"
## [43] "SubSet3" "SubSet3" "SubSet2" "SubSet3" "SubSet2" "SubSet1" "SubSet1"
## [50] "SubSet1"

Naively one would either fill some batches fully or distribute them not evenly (the first 17 packages together, the next 17 and so on). This solution ensures that the data is randomized. For more random distribution you can increase the number of iterations performed to calculate this distribution.

Randomization and replicates

If you need space for replicates to control for batch effect you can use:

repli <- replicates(metadata, size_batch, 5)
lengths(repli)
## SubSet1 SubSet2 SubSet3 
##      21      21      18
repli
## $SubSet1
##  [1]  3  9 10 16 17 20 27 28 30 31 32 33 34 35 40 41 42 44 45 48 49
## 
## $SubSet2
##  [1]  4  5  7  8  9 10 13 15 18 21 22 25 26 32 33 34 36 37 38 39 47
## 
## $SubSet3
##  [1]  1  2  6  9 10 11 12 14 19 23 24 29 32 33 34 43 46 50

Which seeks as controls the most diverse values and adds them to the samples distribution. Note that if the sample is already present on that batch is not added again, that’s why the number of samples per batch is different from the design without replicates.

Layout

We can analyze how these samples would be distributed in a layout of 6x4:

spati <- spatial(repli, metadata, rows = LETTERS[1:6], columns = 1:4)
head(spati)
## $A1
## [1] 21  5 11
## 
## $B1
## NULL
## 
## $C1
## [1] 58 13 33
## 
## $D1
## [1] 35
## 
## $E1
## [1]  3  8 15
## 
## $F1
## [1]  9 19 53

Report for easy on field usage

We can add the batches to the initial data with inspect():

report <- inspect(repli, metadata)
report2 <- inspect(spati, report, index_name = "position")
head(report2)
##   height weight  sex   batch position
## 1     60    100 Male SubSet3       A1
## 2     65    100 Male SubSet3       A1
## 3     70    100 Male SubSet1       A1
## 4     75    100 Male SubSet2       C1
## 5     80    100 Male SubSet2       C1
## 6     60    150 Male SubSet3       C1

And now we can see the batch and position of each sample

Compare indices

If you have two indices you can also compare them:

desi2 <- create_subset(nrow(metadata), size_batch)
compare_index(metadata, desi, desi2)
##         subgroups
##               SubSet1    SubSet2     SubSet3
##   height -0.003378784 -0.4899827  -1.3652524
##   weight -5.083194894 -5.0202051 -12.6611209
##   sex     0.085527089  0.1267009   0.1152791

As many of the variables for multiple subsets are negative it shows that desi is better.

Unbalanced setting

In the previous case the data was mostly balanced (check it out in the orig object) but let’s create an unbalanced dataset to check it.

n <- 99
samples <- 100
unbalanced <- data.frame(Classroom = rep(c("A", "B"), each = samples/2),
                         Sex = c(rep("M", n), rep("F", samples-n)),
                         Age = rnorm(samples, mean = 25, sd = 3))
table(unbalanced[, 1:2])
##          Sex
## Classroom  F  M
##         A  0 50
##         B  1 49

In this dataset there is only one female, resulting in a classroom full of males. Age is independent of the sex or classroom.

i <- design(unbalanced, 15)
## Warning: There might be some problems with the data use check_data().
evaluation <- evaluate_index(i, unbalanced)
## Warning: There might be some problems with the data use check_data().
# Mean entropy en each subset
rowMeans(evaluation["entropy", , ])
##  Classroom        Sex        Age    mix_cat 
## 0.98906095 0.05047991 0.00000000 0.96130358
# Original entropy on the dataset
evaluate_orig(unbalanced)["entropy", ]
## Warning in evaluate_orig(unbalanced): There might be some problems with the
## data use check_data().
##  Classroom        Sex        Age    mix_cat 
## 1.00000000 0.08079314 0.00000000 0.67554928
# Dispersion of the entropy
apply(evaluation["entropy", , ], 1, sd)
##  Classroom        Sex        Age    mix_cat 
## 0.01057627 0.13355727 0.00000000 0.08171973

We can see that in this simple case where a single variable has all the other cases we approximately reached the same entropy levels.

Quality check

If you need a subset with the samples that are more diverse you can use the following function:

data(survey, package = "MASS") 
head(survey)
##      Sex Wr.Hnd NW.Hnd W.Hnd    Fold Pulse    Clap Exer Smoke Height      M.I
## 1 Female   18.5   18.0 Right  R on L    92    Left Some Never 173.00   Metric
## 2   Male   19.5   20.5  Left  R on L   104    Left None Regul 177.80 Imperial
## 3   Male   18.0   13.3 Right  L on R    87 Neither None Occas     NA     <NA>
## 4   Male   18.8   18.9 Right  R on L    NA Neither None Never 160.00   Metric
## 5   Male   20.0   20.0 Right Neither    35   Right Some Never 165.00   Metric
## 6 Female   18.0   17.7 Right  L on R    64   Right Some Never 172.72 Imperial
##      Age
## 1 18.250
## 2 17.583
## 3 16.917
## 4 20.333
## 5 23.667
## 6 21.000
samples <- extreme_cases(survey, size = 10)
survey[samples, ]
##        Sex Wr.Hnd NW.Hnd W.Hnd    Fold Pulse    Clap Exer Smoke Height      M.I
## 41  Female   17.5   16.0 Right  L on R    NA   Right Some Never 169.00   Metric
## 52    Male   20.5   20.0 Right  L on R    68   Right Freq Never 190.00   Metric
## 76  Female   17.5   17.5 Right Neither    68   Right Freq Heavy 170.00   Metric
## 82    Male   19.2   18.9 Right  R on L    76   Right Freq Never 176.50 Imperial
## 93  Female   18.2   17.5 Right  L on R    70   Right Some Never 165.00   Metric
## 137   <NA>   19.8   19.0  Left  L on R    73 Neither Freq Never 172.00   Metric
## 139   Male   20.0   19.5 Right  L on R    NA   Right Freq Never 170.00   Metric
## 142 Female   18.3   19.0 Right  R on L    NA   Right None Never 165.00   Metric
## 154   Male   21.5   21.6 Right  R on L    69   Right Freq Never 172.72 Imperial
## 221   Male   23.2   23.3 Right  L on R    NA   Right None Heavy 171.00   Metric
##        Age
## 41  17.500
## 52  17.500
## 76  20.667
## 82  20.167
## 93  19.667
## 137 21.500
## 139 21.417
## 142 21.083
## 154 70.417
## 221 20.917

You can also test a given index with check_index():

check_index(unbalanced, i)
## Warning in check_index(unbalanced, i): There might be some problems with the
## data use check_data().
##            subgroups
##                SubSet1    SubSet2    SubSet3    SubSet4    SubSet5    SubSet6
##   Classroom 0.02244529 0.03105896 0.02629978 0.02137583 0.02137583 0.02629978
##   Sex       0.16047517 0.22439953 0.16047517 0.16047517 0.16047517 0.16047517
##   Age       0.42561876 0.23886131 0.43542914 0.19353035 0.12717736 0.34552062
##   mix_cat   0.08031059 0.02527493 0.07741971 0.08111268 0.08111268 0.07741971
##            subgroups
##                SubSet7
##   Classroom 0.02629978
##   Sex       0.16047517
##   Age       0.25569779
##   mix_cat   0.07741971

Each row has information about how accurate is a given variable to the samples available (on this case unbalanced). Some variables are distributed more randomly than others on this index.

If we are not satisfied we could design() a new index increasing the iterations to obtain a potentially better distribution. If you want a good stratified randomization you should increase the iterations used 10 fold.

Internals

We could check all the combinations to select those that allow us to do this comparison. But as this would be too long with experDesign we can try to find the combination with the best design by comparing each combination with the original according to multiple statistics.

# To reduce the variables used:
omit <- c("Wr.Hnd", "NW.Hnd", "Fold", "Pulse", "Clap", "Exer", "Height", "M.I")
(keep <- colnames(survey)[!colnames(survey) %in% omit])
## [1] "Sex"   "W.Hnd" "Smoke" "Age"
head(survey[, keep])
##      Sex W.Hnd Smoke    Age
## 1 Female Right Never 18.250
## 2   Male  Left Regul 17.583
## 3   Male Right Occas 16.917
## 4   Male Right Never 20.333
## 5   Male Right Never 23.667
## 6 Female Right Never 21.000

# Set a seed for reproducibility
# Looking for groups at most of 70 samples.
index <-  create_subset(nrow(survey), size_subset = 70)
index
## $SubSet1
##  [1]   6  13  14  15  16  17  20  26  32  34  37  47  48  51  53  56  58  59  63
## [20]  64  67  75  77  79  80  81  85  95 102 108 111 114 115 118 119 126 130 131
## [39] 134 136 154 156 161 180 182 183 189 192 194 202 203 209 210 211 214 224 225
## [58] 228 229 236
## 
## $SubSet2
##  [1]   3   4   5   8  12  19  22  24  25  28  31  38  45  46  66  68  70  72  78
## [20]  82  87  91  97  98 104 106 107 112 121 128 129 141 142 149 150 152 153 159
## [39] 163 165 166 167 174 176 184 188 190 191 195 198 212 216 219 221 223 231 232
## [58] 234 237
## 
## $SubSet3
##  [1]   2   7  10  23  27  30  33  39  42  49  52  60  61  62  69  71  73  74  86
## [20]  88  89  90  94 103 109 113 116 117 123 132 133 135 140 146 151 157 158 160
## [39] 169 171 172 173 175 181 185 187 199 205 206 207 208 213 215 217 222 226 227
## [58] 230 235
## 
## $SubSet4
##  [1]   1   9  11  18  21  29  35  36  40  41  43  44  50  54  55  57  65  76  83
## [20]  84  92  93  96  99 100 101 105 110 120 122 124 125 127 137 138 139 143 144
## [39] 145 147 148 155 162 164 168 170 177 178 179 186 193 196 197 200 201 204 218
## [58] 220 233

We can measure how does this index does:

score_index1 <- check_index(survey[, keep], index)
## Warning in check_index(survey[, keep], index): There might be some problems
## with the data use check_data().
score_index1
##          subgroups
##               SubSet1    SubSet2    SubSet3    SubSet4
##   Sex     0.183272313 0.18307418 0.18473404 0.34995773
##   W.Hnd   0.201330461 0.38189871 0.16814879 0.16765764
##   Smoke   0.384839974 0.51271703 0.34958370 0.36736401
##   Age     0.247117147 0.86678868 0.69125158 0.51061368
##   mix_cat 0.006173258 0.01392375 0.01709306 0.03849348

These values come from calculating the difference between the original data and the samples for each subset for the median, mean, mad, NA, entropy and independence (chisq.test() p.value).

On themselves these values have no meaning, but internally they are used to compare with other possible index:

index2 <- create_subset(nrow(survey), size_subset = 70)

Then it compares to the previous index

score_index2 <- check_index(survey[, keep], index2)
## Warning in check_index(survey[, keep], index2): There might be some problems
## with the data use check_data().
sum(rowMeans(abs(score_index2-score_index1)))
## [1] 0.9367265

If this score is lower than the previous one the new index is kept.

This is done similarly for the spatial search, which adds two new categorical variables with the position of the samples before calculating any statistics.

SessionInfo

sessionInfo()
## R version 4.3.1 (2023-06-16)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 22.04.4 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so;  LAPACK version 3.10.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=ca_ES.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=ca_ES.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=ca_ES.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=ca_ES.UTF-8 LC_IDENTIFICATION=C       
## 
## time zone: Europe/Madrid
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] experDesign_0.3.0
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.34     R6_2.5.1          fastmap_1.1.1     xfun_0.42        
##  [5] cachem_1.0.8      knitr_1.45        htmltools_0.5.7   rmarkdown_2.25   
##  [9] lifecycle_1.0.4   cli_3.6.2         sass_0.4.8        jquerylib_0.1.4  
## [13] compiler_4.3.1    rstudioapi_0.15.0 tools_4.3.1       evaluate_0.23    
## [17] bslib_0.6.1       yaml_2.3.8        rlang_1.1.3       jsonlite_1.8.8