[R] Help with tryCatch with a for loop
Spencer S
scheidt14 at gmail.com
Wed Nov 9 18:00:01 CET 2011
Hello all,
I'm a beginner in R working on a script that will produce a set of models
(linear, polynomial and logistic) for each location in a dataset. However,
the self-starting logistic model often fails - if this happens I would like
to just skip to the next iteration of the loop using tryCatch.
I've looked at a few examples and read the help file, but didn't understand
tryCatch in the context of my script. Any help or suggestions (even telling
me where to insert the tryCatch command) would be much appreciated!!
Below is the script I am currently working on:
data<-read.csv(file.choose(),sep=",",header=T)
#File name is cbc.subset
data$location.code = as.character(data$location.code)
locs = unique(location.code)
pdf("mygraphs.pdf",height=8, width=10)
par(mfrow=c(3,4))
for(s in 1:length(locs)){
#To plot data from a particular stateroute:
sub.ECDO<-data[data$location.code == locs[s],]
plot(abund~year, data=sub.ECDO, main=locs[s])
#To plot the linear model for the specified location:
lmodel<-lm(abund~year, data=sub.ECDO)
abline(lmodel$coefficients[1],lmodel$coefficients[2],lty=2)
#To plot the polynomial model for the specified location:
polymodel<-lm(abund~year+I(year^2), data=sub.ECDO)
xv<-seq(min(sub.ECDO$year),max(sub.ECDO$year),0.1)
yv<-predict(polymodel,list(year=xv))
lines(xv,yv)
#To plot the logistic model
#####tryCatch
logis<-nls(abund~SSlogis(year,a,b,c),data=sub.ECDO)
yv<-predict(logis,list(year=xv))
lines(xv,yv)
#To find which model is the best fit:
if ("logis" %in% ls()) {
AIC.results = AIC(lmodel,polymodel,logis)
} else {
AIC.results = AIC(lmodel,polymodel)
}
#Add text to plot
text(min(sub.ECDO$year)+2,0.9*max(sub.ECDO$abund),paste("linear =
",AIC.results[1,2],"\npolynomial = ",AIC.results[2,2],"\nlogistic =
",AIC.results[3,2],sep=""))
rm(logis)
rm(polymodel)
rm(lmodel)
}
dev.off()
Thank you!
--
View this message in context: http://r.789695.n4.nabble.com/Help-with-tryCatch-with-a-for-loop-tp4020475p4020475.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list