Lecture2 <- function() { # Ex1() # Ex2() # GenData() Ex3() } # ============================================================================================================================================ Ex1 <- function() { vals <- c(0.05,0.1,0.25,0.5,1,1.5,2,2.5,5) Ex1a(vals) } # ============================================================================================================================================ Ex1a <- function(periods) { par(mfrow=c(3,3)) xx <- seq(from=0,to=2*pi,length=100) for (ii in 1:length(periods)) plot(xx,sin(xx/periods[ii]),main=periods[ii],type='l') } # ============================================================================================================================================ Ex2 <- function() { Long <- NULL for (i in 1:1000) { Age <- 0; alive <- T # Continue incrementing age while the animal is still aline while(alive) { if (runif(1) < 0.3) alive <- F else Age <- Age + 1 } # the age of the animl of the age before it died to the list Long <- c(Long,Age) } hist(Long) } # ============================================================================================================================================ GenData <- function() { FileName <- "K:\\Lect2.csv" set.seed(1) Npop <- 20 Nsamp <- sample(c(1:8),Npop,replace=TRUE) print(Nsamp) IntC <- rep(0,length=Npop) Slope <- rnorm(Npop,3,0.5) print(Slope) Outs <- matrix(0,ncol=3,nrow=sum(Nsamp)) Ipnt <- 0 for (II in 1:Npop) for (JJ in 1:Nsamp[II]) { Ipnt <- Ipnt + 1 Outs[Ipnt,1] <- II Outs[Ipnt,2] <- JJ Outs[Ipnt,3] <- IntC[II] + Slope[II]*JJ+rnorm(1,0,1) } print(Outs) write.table(Outs,file=FileName,col.names=F,sep=',') } # ============================================================================================================================================ Ex3 <- function() { # Read in the data FileName <- "I:\\Lect2.csv" TheData <- read.table(FileName,sep=',') Nmax <- max(TheData[,2]) # Create a list of zero length Slopes <- NULL # Work through each animal in turn for (Ipop in 1:Nmax) { # Extract the data for this animal TheDat1 <- TheData[TheData[,2]==Ipop,] # If enough data if (length(TheDat1[,1]) > 1) { RegOut <- lm(TheDat1[,4]~TheDat1[,3]) TheSlope <- coefficients(RegOut)[2] Slopes <- c(Slopes,TheSlope) } } hist(Slopes,xlab="Slope",main="") } # ============================================================================================================================================ Lecture2()