Skip to content

Instantly share code, notes, and snippets.

@sdtaylor
Last active February 27, 2018 16:20
Show Gist options
  • Save sdtaylor/ff79ba074cdac613f940e06c3b1f5d91 to your computer and use it in GitHub Desktop.
Save sdtaylor/ff79ba074cdac613f940e06c3b1f5d91 to your computer and use it in GitHub Desktop.
download climate locations for a single location
library(lubridate)
library(dplyr)
####################################################################################
#' Download downscaled climate forecast data
#'
#' Individual climate models available are are c('CFSv2','CMC1','CMC2','GFDL-FLOR','GFDL','NASA','NCAR'),
#' 'ENSMEAN' is the mean of all models.
#' lead_time is the months into the future to obtain forecasts. Max of 7
#' Default lat and lon are for Portal, AZ
get_climate_forecasts = function(climate_model = 'ENSMEAN',
lat = 31.9555, lon = -109.0744,
lead_time = 6){
if(!climate_model %in% c('CFSv2','CMC1','CMC2','GFDL-FLOR','GFDL','NASA','NCAR')) stop(paste0('Unknown climate model: ',climate_model))
if(!lead_time %in% 1:7) stop(paste0('Lead time must an integer be between 1 and 7, got: ',lead_time))
today = Sys.Date()
start_time = strftime(today, format='%Y-%m-%d')
end_time = strftime(today %m+% months(lead_time), format='%Y-%m-%d')
# add in timestamps for URL
start_time = paste0(start_time,'T00%3A00%3A00Z')
end_time = paste0(end_time,'T00%3A00%3A00Z')
full_url = paste0('https://tds-proxy.nkn.uidaho.edu/thredds/ncss/NWCSC_INTEGRATED_SCENARIOS_ALL_CLIMATE/bcsd-nmme/monthlyForecasts/bcsd_nmme_metdata_',climate_model,
'_forecast_1monthAverage.nc?var=prate&var=tmp2m&latitude=',lat,'&longitude=',lon,'&time_start=',start_time,'&time_end=',end_time,'&accept=csv')
raw_download = RCurl::getURL(full_url)
df=read.table(sep=',',skip=1,text=raw_download)
colnames(df) = c('date','lat','lon','precip','temperature')
df = df %>%
mutate(date = as_date(date)) %>%
mutate(year = year(date), month=month(date)) %>%
select(-date, -lat, -lon)
return(df)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment