[R] Help with tryCatch

John Sorkin jsorkin at grecc.umaryland.edu
Sat Jan 2 04:27:26 CET 2010


Windows XP
R 2.8.1

Colleagues,
I am trying to run a function testone() and if the function completes without error do one set of instructions, and if the function generates either a warning or an error run another set of instructions. I have read try, and tryCatch help screens at least 20 times, have tried to experiment with code, but I can't understand how to accomplish my desired task. Perhaps I need to use withCallingHandlers(), but the explanation of these functions is beyond my ken. My latest code follows. Any suggestions for corrections would be appreciated.

# Define matrix to hold results
coeffs <- matrix(nrow=10, ncol=3)
dimnames(coeffs) < -list(NULL,c("BMI","BMIsq","min"))

# set row counter
n<-0

# Function to run
testone<-function()
{
SampleData<-sample(1:SS,size=SS,replace=TRUE)
result<-summary(glm(AAMTCARE~BMIEpiRevAdjc+BMIEpiRevAdjcSq+SEX+jPHI+jMEDICAID+H_AGE+jMARSTAT+factor(jEDUCATION)+factor(jsmokercat)+factor(jrace)+log(INCOME_C+1),data=SimData[SampleData,],family=Gamma(link="log")))
}

# if function ran correctly, increment row counter by one and store results
# Do this 10 times
while (n<10) {
  result<-tryCatch(testone(),final=n<-n+1)

# Do the function ran without an error
  result
  coeffs[n,1] <- result$coefficients[2,1]
  coeffs[n,2] <- result$coefficients[3,1] 
  coeffs[n,3] <-  -(coeffs[n,1])/(2*coeffs[n,2])
  print(n)
  print(coeffs)

# if function returned with either a warning or error do not increment row counter, do not store results
# I have no idea how to get to this code!
# I need to know if an error code has been raised
}


Thank you,
John



John David Sorkin M.D., Ph.D.
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing)

Confidentiality Statement:
This email message, including any attachments, is for th...{{dropped:6}}



More information about the R-help mailing list