My ultimate goal is to use R to model hourly temperatures from daily temperature maxima and minima, spanning the years 1986 to 2017. I've successfully written code for a single date's data, but am having trouble applying this code across many dates.
I obtained daily temperature data from the National Resource Conservation Service (NRCS) for my focal site here: https://wcc.sc.egov.usda.gov/nwcc/site?sitenum=526
Following a model published here:
Reicosky, D.S., Winkelman, L.J., Baker, J.M., Baker, D.G. 1989. Accuracy of hourly air temperatures calculated from daily minima and maxima. Agricultural and Forest Meteorology. 46:193-209
I wrote the following code, which works great for modelling a single day's hourly temperature data:
#create df for SINGLE DATE.
#The actual data frame that I wish to model temperatures from will be exactly like this
#but with 11,689 rows.
d8a <- data.frame(
Day.of.Year = 213,
Date = as.Date("01-Aug-2011",format = "%d-%b-%Y"),
SunRise_decimal = 4.9,
Air.Temperature.Minimum..degC. = 8.0,
Air.Temperature.Maximum..degC. = 22.1
)
#create matrix to serve as repository for modeled hourly temp data
OneDay <- data.frame(OneDay <- matrix(0, ncol = 0, nrow = 24))
hour <- OneDay$hour <- c(0:23)
rise <- OneDay$sunrise <- d8a$SunRise_decimal
tmax <- OneDay$tmax <- d8a$Air.Temperature.Maximum..degC.
tmin <- OneDay$tmin <- d8a$Air.Temperature.Minimum..degC.
tavg <- OneDay$tavg <- (OneDay$tmax + OneDay$tmin) / 2
peakhour <- OneDay$peakhour <- 14
amp <- OneDay$amp <- (OneDay$tmax - OneDay$tmin)/2
#Now for the actual modelling:
OneDay$tmod <- ifelse(hour < rise, tavg + amp * cos(pi * (hour + 10) / (10 + rise)),
ifelse(hour > peakhour, tavg + amp * cos(pi * (hour - peakhour) / (10 + rise)),
ifelse(hour >= rise, tavg - amp * cos(pi * (hour - rise) / (peakhour - rise)),
99999)))
plot(tmod ~ hour, data = OneDay, pch = 19, cex = 1.5, ylim = c(8,23),
main = "01 August 2011", las = 1, ylab = "Temp (C)", xlab = "Hour of Day")
lines(tmod ~ hour, data = OneDay)
Finally, my question:
How can I iterate this code (or a more efficient version of this code) over every date in a data frame comprised of many dates?
I realize the final data set will be huge. ((31 years * 365 days per year * 24 hours per day) = 280,320 rows)