简体   繁体   中英

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")))
}

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(){})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM