Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aggregate.R created #3317

Merged
merged 17 commits into from
Jul 25, 2024
Merged
36 changes: 36 additions & 0 deletions modules/assim.sequential/R/aggregate.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
##' @title Aggregation Function
##' @name aggregate
##' @author Harunobu Ishii
##'
##' @param downscale_output Raster file output from downscale_function.R. Read file in this way if stored locally: \code{downscale_output <- readRDS("xxx.rds")}
##' @param polygon_data A spatial polygon object (e.g., an `sf` object) that defines the spatial units for aggregation.
##' This data should be in a coordinate reference system compatible with the raster data (e.g., "EPSG:4326").
##' Example of state-level aggregation:
##' \code{
##' us_states <- readRDS("polygon/us_states.rds")
##' state <- "MA"
##' polygon_data <- st_transform(us_states[us_states$STUSPS == state, ], crs = "EPSG:4326")
##' }
##' @details This function will aggregate previously downscaled carbon flux amount to a spatial unit of choice
##'
##' @return It returns the `polygon_data` with added columns for mean and sum values of the aggregated raster data for each ensemble member.
Snafkin547 marked this conversation as resolved.
Show resolved Hide resolved


library(exactextractr)
library(terra)
library(sf)
Snafkin547 marked this conversation as resolved.
Show resolved Hide resolved

aggregate <- function(downscale_output, polygon_data){

# Perform spatial operations on each raster
for (name in names(downscale_output$maps)) {
raster_data <- downscale_output$maps[[name]]

mean_values <- exact_extract(raster_data, polygon_data, fun = 'mean')
sum_values <- exact_extract(raster_data, polygon_data, fun = 'sum')

polygon_data[[paste0(name, "_mean")]] <- mean_values
polygon_data[[paste0(name, "_sum")]] <- sum_values
Snafkin547 marked this conversation as resolved.
Show resolved Hide resolved
}
return (polygon_data)
}