Skip to content

Instantly share code, notes, and snippets.

@amoeba
Created September 19, 2016 17:51
Show Gist options
  • Select an option

  • Save amoeba/2303bc61773d8db085e5020ce831da9d to your computer and use it in GitHub Desktop.

Select an option

Save amoeba/2303bc61773d8db085e5020ce831da9d to your computer and use it in GitHub Desktop.
#' overnight_temps.R
#' https://twitter.com/AbsLawson/status/777799977393270784
#'
#' rstats q: want to calc overnight temp (~22:00-4:00) from hrly temps w/ missing
#' values (rows). Desired timespan overlaps dates, unsure how
# Create dummy data to use
df <- data.frame(datetime = seq(ISOdate(2016,1,1), ISOdate(2016,3,1), by = "hour"))
df$temp_c <- runif(nrow(df), 0, 20)
#' Calculate day of year and hour of day
#'
#' I always try to work in 'ordinal' dates and times because comparing dates
#' seems to be so finicky
df$day_of_year <- as.numeric(format(df$datetime, "%j"))
df$hour_of_day <- as.numeric(format(df$datetime, "%H"))
#' Here I Calculate "daily means" where daily is your definition of 2200 to 0400
#' the next day. I use an lapply() here but you could also do a for loop.
lapply(unique(df$day_of_year), function(day) {
mean(df[(df$day_of_year == day & df$hour_of_day >= 22) | (df$day_of_year == (day + 1) & df$hour_of_day <= 4),"temp_c"])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment