Link to home

Generating Random Values

A series of 20 fair (equal probability of head=1 or tail=0) coin flips can be generated by the random binomial generator

rbinom(n=20, size=1, prob=0.5)
# size indicates the number of flips in each of the 20 trials

Samples from a set of numbers or names can be drawn.

sample(20)  # this arranges 1:20 in random order
sample(20,5) # this draws 5 samples from 1:20
sample(20, replace=T)

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 <- 8
nrepl <- 2
sample(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 dimension
temp <- 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 information
matrix(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 <- 8
nrepl <- 1
sample(1:ntrt)
# Suppose nrepl is greater than 1
nrepl <- 5
randout <- sample(1:ntrt)
for (j in 2:nrepl){randout <- c(randout,sample(1:ntrt))}
# If the blocks should appear in the map as columns
matrix(randout,nrow=ntrt,ncol=nrepl)

 

 

Next: Statistical Distributions