getwd() # Get current working directory
## [1] "C:/Users/Juan Steibel/AppData/Local/Temp/RtmpSSuXJB"
#setwd("C:/Users/steibelj/OneDrive/Documents/job/ans824/2015") # Set current working
setwd("C:/Users/Juan Steibel/SkyDrive/Documents/job/ans824/2015")
rm(list=ls()) # Remove all objects from work environment
cnt<-read.table("counts.txt",header=T)
Alternative activity
code to make loopless
mcnt<-as.matrix(cnt)
mean_cnt<-matrix(0,nrow(cnt),24)
var_cnt<-matrix(0,nrow(cnt),24)
# 1) we need a loop over the rows of cnt:
system.time({
for (i in 1:nrow(cnt)) { #this is a loop from 1 to the number of rows of cnt
# 2) we now transform the row of 96 observations into a matrix of 4 by 24:
vec_count<-matrix(mcnt[i,],4,24,byrow=F) #notice we need to fill the matrix
#column wise
#notice unlist, necesary to get correct format
# 3) now we compute the column means
mean_sample<-colMeans(vec_count)
# 4) now we compute the column variances (diagonal of variance-covariance matrix)
var_sample<-diag(var(vec_count))
# 5) we "grow" the matrix of results
mean_cnt[i,]<-mean_sample
var_cnt[i,]<-var_sample
# 6) close the loop and back
}
})
a function that will facilitate the implementation:
inputvec (a row of counts)nrep (number of technical reps, by default 4)operator (a text: mean or var)
restrictions:vec should be numericlength(vec)/nrep should be an integer number
compute_stat<-function(vec,nrep=4,operator="mean"){
if (!is.vector(vec)) stop ("vec should be a vector")
if (!is.numeric(vec)) stop ("vec should be numeric")
if (!((length(vec)%%nrep)==0)) stop ("length of vec should be multiple of nrep")
if ((operator!="mean")&(operator!="var")) stop ("operator should be either mean or var")
nc<-length(vec)/nrep
vec_count<-matrix(vec,nrep,nc,byrow=F)
if (operator=="mean") {
result<-colMeans(vec_count)
} else {
result<-diag(var(vec_count))
}
return(result)
}
sugested activities
-explain each step of the function
-apply the function and test it for accuracy