Created
July 18, 2025 05:15
-
-
Save johnbaums/194861e343fd1a51e6bc07182f7ed2c7 to your computer and use it in GitHub Desktop.
Calculate average monthly day length (rast)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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