Bailes
Bailes

Reputation: 55

Trycatch in for loop- continue to next r dataRetrieval

I have a list containing the following site id numbers: sitelist <- c("02074500", "02077200", "208111310", "02081500", "02082950")

I want to use the dataRetrieval package to collect additional information about these sites and save it into individual .csv files. Site number "208111310" does not exist, so it returns an error and stops the code.

I want the code to ignore site numbers that do not return data and continue to the next number in sitelist. I've tried trycatch in several ways but can't get the correct syntax. Here is my for loop without trycatch.

for (i in sitelist){
    test_gage <- readNWISdv(siteNumbers = i,
                      parameterCd = pCode)

    df = test_gage
    df = subset(df, select= c(site_no, Date, X_00060_00003))
    names(df)[3] <- c("flow in m3/s")
    df$Year <- as.character(year(df$Date))

    write.csv(df, paste0("./gage_flow/",i,".csv"), row.names = F)
    rm(list=setdiff(ls(),c("sitelist", "pCode")))
}

Upvotes: 1

Views: 197

Answers (1)

Manos Papadakis
Manos Papadakis

Reputation: 593

You can use the variable error in the function trycatch to specify what happened when an error occurs and store the return value using operator <<-.

for (i in sitelist){ 
    test_gage <- NULL
    trycatch(error=function(message){         
        test_gage <<- readNWISdv(siteNumbers = i,parameterCd = pCode) 
    }
    df = test_gage 
    df = subset(df, select= c(site_no, Date, X_00060_00003)) 
    names(df)[3] <- c("flow in m3/s") 
    df$Year <- as.character(year(df$Date))    write.csv(df, paste0("./gage_flow/",i,".csv"), row.names = F) 
    rm(list=setdiff(ls(),c("sitelist", "pCode"))) 
}

If you want to catch the warnings also just give a second argument to trycatch.

trycatch(error=function(){},warning=function(){})

Upvotes: 1

Related Questions