The last example draws 20 samples from 1:20 with replacement, while the default is to sample without replacement. Use the help command to find more information about sample and paste.

x24 <-paste('trt',1:10,sep='')sample(x24,5)

Example: Generating Randomized Treatment Maps

You can use random numbers and sampling in R to generate maps of treatments for experiments. For example, a completely randomized design assigns a set of treatments to experimental units at random throughout the set of experimental units. This is in contrast to a randomized complete block design, where each treatment is assigned to one experimental unit within a block. The easiest ways to conceptualize such experimental designs may be in the context of a field study in which a unit of land or a plot is an experimental unit or in terms of a greenhouse study in which a pot on a bench is an experimental unit.

For a completely randomized design, suppose there are ntrt treatments labeled 1 through ntrt, and nrepl replicates. The set of random treatment assignments can be generated by the following code, where arbitrary values of ntrt and nrepl are supplied as an example:

ntrt <-8nrepl <-2sample(rep(x=1:ntrt,times=nrepl))# These treatments can be assigned to a map with# particular dimensions by putting the values# in a matrix of desired dimensiontemp <-sample(rep(x=1:ntrt,times=nrepl))# note that the function ‘rep’ already exists in R# and is not to be confused with our new variable ‘nrepl’# try ‘help(rep)’ for more informationmatrix(temp,nrow=nrepl,ncol=ntrt)

For a randomized complete block design, each treatment has to be assigned once within each block before the same treatment can be assigned again. If nrepl = 1 (an unrealistic case), then the order of treatments can be randomized by:

ntrt <-8nrepl <-1sample(1:ntrt)# Suppose nrepl is greater than 1nrepl <-5randout <-sample(1:ntrt)for(j in2:nrepl){randout <-c(randout,sample(1:ntrt))}# If the blocks should appear in the map as columnsmatrix(randout,nrow=ntrt,ncol=nrepl)