Sunday 20 January 2013

R-code for Showing Two Overlapping Normal Distributions

This is the code that I use to show how normal distributions overlap and how to find the right sample size to be able to distinguish the two alternatives.



dat <- read.table(text="info mean sd
                   HYP1 10 0.2
                   HYP2 12 0.2", header =T)
dat <- transform(dat, lower=mean-4*sd, upper=mean+4*sd) #create upper and lower bounds for the plot
plot(x=c(min(dat$lower)-2, max(dat$upper)+2), y=c(0, 2), ylab="", 
     xlim=c(min(dat$lower)-2, max(dat$upper)+2),xlab="",
     axes=FALSE, xaxs="i", type="n")
box()
FUN <- function(rownum){
  par(new=TRUE)
  curve(dnorm(x,dat[rownum,2], dat[rownum, 3]),
        xlim=c(c(min(dat$lower)-2, max(dat$upper)+2)),
        ylim=c(0, 2),
        ylab="", xlab="")
}
lapply(seq_len(nrow(dat)), function(i) FUN(i))


No comments: