## this queries the single-pixel extraction tool for DayMet weather ranging from startyear to endyear
#longvector: vector of longitudes
#latvector: vector of latitudes
#startyear: starting year for weather file
#endyear: ending year for weather file
#namevector: name to add to the file that gets written
daymet_weathergrab <- function(latvector,longvector,startyear,endyear,namevector)
{
latvector <- as.character(latvector) # convert to char type in case they're not already
longvector <- as.character(longvector)
startyear <- as.character(startyear)
endyear <- as.character(endyear)
namevector <- as.character(namevector)
for (i in 1:length(latvector))
{
download.file(url=paste0("https://daymet.ornl.gov/single-pixel/api/data?lat=",latvector[i],"&lon=",longvector[i],"&vars=tmax,tmin,prcp,srad&start=",startyear,"-01-01&end=",endyear,"-12-31"),
destfile=paste0(namevector[i],"_",latvector[i],"_",longvector[i],".dmw"))
}
}
#example:
daymet_weathergrab( latvector=c(26,30,38), longvector=c(-98,-96,-92), startyear=1979, endyear=2000, namevector=c("foo","bar","foobar") )
##this reads in a list of DayMet weather (.dmw) files and converts them to DayCent weather (.wth) format
# DayCent files get the same name as the input dmw files, but with swapped extensions
# following is how I make the list of files:
# mydmwfiles <- list.files(path = "weather", pattern = "dmw", full.names = T)
#REQUIRES the lubridate and stringr libraries
daymet_to_daycent <- function(mydmwfiles)
{
library(lubridate)
library(stringr)
for (j in 1:length(mydmwfiles))
{
dmw <- read.table(file=mydmwfiles[j], skip = 7, header=T, sep=",") #skips 7-line header in DayMet
dmw$date <- as.Date(dmw$yday-1, origin=paste(dmw$year,"01","01",sep="-")) #converts year-doy from the DayMet file into a date-class so that other values (day of month, month of year) can be extracted for the .wth file
wth <- cbind(mday(dmw$date),month(dmw$date),year(dmw$date),yday(dmw$date),dmw$tmax..deg.c.,dmw$tmin..deg.c.,dmw$prcp..mm.day./10) #reorders and converts the DayMet data fields to DayCent format
wthname <- str_replace(string=mydmwfiles[j], pattern="dmw", replacement="wth") #make the string for naming the .wth output file
write.table(x=wth,file=wthname,quote=F,row.names=F,col.names=F,sep="\t") #writes out the file without extra junk
}
}
# example: daymet_to_daycent("foobar_38_-92.dmw")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.