I am trying to pull out all United States Geological Survey (USGS) sites that have daily mean water temperature for a given date range using the USGS package dataRetrieval. I can do this with a for loop that iterates through each US state/territory abbreviation but the loop stops running once it comes across a location that does not have any sites. How can I make the loop skip locations that do no have sites available?
This is the for loop that works but stops when it comes across a state/territory that does not have a site.
library(dataRetrieval)
statCd <- "00003" # Mean
startDate <- "1990-01-01"
endDate <- "2019-12-31"
states <- stateCd
# For loop determines how many sites have daily avg. water temp. data records for period of interest
for(i in 1:length(states)) {
tempDat_states = whatNWISdata(stateCd = states[i],
parameterCd = "00010") # Water temperature
temp_states = tempDat_states %>%
filter(stat_cd == "00003") %>%
mutate(period = as.Date(endDate) - as.Date(startDate))
temp_states$end_year <- year(temp_states$end_date)
temp_states$start_year <- year(temp_states$begin_date)
temp_states <- temp_states[temp_states$start_year <= 1990 & temp_states$end_year >= 2019,]
curDat_temp = temp_states
curDat_temp$STUSAB = states[i]
if( i == 1){
saveDat_temp = curDat_temp
} else{
saveDat_temp = rbind(saveDat_temp, curDat_temp)
}
}
The for loop below is the same as above, but I have manually kept only the states/territories that have sites available. I would like to avoid having to manually identify and keep those states/territories, so any code that skips those locations (maybe using next?) in the for loop would be what I'm looking for.
# Remove AR, DO, HI, ID, IA, MA, NE, NH, OK, RI, SD, VT, AS, GU, MP, PR, UM, VI for having zero sites
states <- stateCd[c(1:3,5:8,10:11,14:15,17:21,23:27,29,31:36,38:39,41,43:45,47:51),2]
for(i in 1:length(states)) {
tempDat_states = whatNWISdata(stateCd = states[i],
parameterCd = "00010") # Water temperature
temp_states = tempDat_states %>%
filter(stat_cd == "00003") %>%
mutate(period = as.Date(endDate) - as.Date(startDate))
temp_states$end_year <- year(temp_states$end_date)
temp_states$start_year <- year(temp_states$begin_date)
temp_states <- temp_states[temp_states$start_year <= 1990 & temp_states$end_year >= 2019,]
curDat_temp = temp_states
curDat_temp$STUSAB = states[i]
if( i == 1){
saveDat_temp = curDat_temp
} else{
saveDat_temp = rbind(saveDat_temp, curDat_temp)
}
}