Skip to content

Instantly share code, notes, and snippets.

@johnbaums
Created July 18, 2025 05:15
Show Gist options
  • Save johnbaums/194861e343fd1a51e6bc07182f7ed2c7 to your computer and use it in GitHub Desktop.
Save johnbaums/194861e343fd1a51e6bc07182f7ed2c7 to your computer and use it in GitHub Desktop.
Calculate average monthly day length (rast)
average_daylength_for_month <- function(month, rast) {
require(chillR)
require(terra)
ndays <- lubridate::days_in_month(month)
jdays <- sprintf("%02d-%02d-2025", 1:ndays, month) |>
lubridate::dmy() |>
lubridate::yday()
lats <- terra::yFromRow(rast, seq_len(nrow(rast)))
daylengths <- sapply(lats, function(lat) {
chillR::daylength(lat, jdays)$Daylength
})
mean_daylengths <- colMeans(daylengths)
out <- terra::init(rast[[1]], NA)
values(out) <- rep(mean_daylengths, each = ncol(rast))
out
}
# r <- terra::rast(res = 1)
# jan <- average_daylength_for_month(1, r)
# all <- lapply(1:12, average_daylength_for_month, r) |>
# terra::rast() |>
# setNames(month.abb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment