Last active
October 25, 2023 13:31
-
-
Save DDorch/ab390d776592adabcd3f0347201c4692 to your computer and use it in GitHub Desktop.
Spatial aggregation containing NA values with stars R package
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
| library(stars) | |
| # USA states | |
| nc = sf::read_sf(system.file("gpkg/nc.gpkg", package = "sf"), "nc.gpkg") | |
| nc = st_transform(nc, "OGC:CRS84") | |
| # Coarse grid upon the map | |
| bb <- as.list(round(st_bbox(nc))) | |
| x <- seq(bb$xmin, bb$xmax) | |
| y <- seq(bb$ymin, bb$ymax) | |
| df <- expand.grid(x = x, y = y) | |
| df$value = runif(nrow(df)) + 10 | |
| df$value[seq(1,nrow(df), 3)] <- NA | |
| star <- st_as_stars(df, dims = c("x", "y")) | |
| st_crs(star) <- st_crs(nc) | |
| # Check the grid vs map with | |
| ggplot() + geom_stars(data = star) + geom_sf(data = st_geometry(nc), fill = NA) | |
| # Spatial Aggregation | |
| agg <- aggregate(star, st_geometry(nc), mean) | |
| plot(agg) | |
| # Try with coverage_fraction | |
| agg <- aggregate(star, st_geometry(nc), mean, exact = TRUE) | |
| plot(agg) | |
| agg <- aggregate(star, st_geometry(nc), mean, exact = TRUE, na.rm = TRUE) | |
| plot(agg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment