generated from NOAA-OWP/owp-open-source-project-template
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbuild_grid.R
More file actions
30 lines (24 loc) · 815 Bytes
/
build_grid.R
File metadata and controls
30 lines (24 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#' Build Vector based Grid of input
#' @param file path to a gridded file (either .tif or .nc)
#' @param geom sf object of aggregation units
#' @return
#' @export
#' @examples
#' @importFrom dplyr mutate
#' @importFrom spex qm_rasterToPolygons
#' @importFrom raster crop raster stack
#' @importFrom sf st_crs st_transform
build_grid = function(file, geom){
r = suppressWarnings(raster::raster(file) )
y.dim = dim(r)[1]
x.dim = dim(r)[2]
cols <- rows <- r
cols[] = (rep(1:y.dim, each = x.dim))
names(cols) = 'Y'
rows[] = (rep(1:x.dim, times = y.dim))
names(rows) = 'X'
raster::stack(cols, rows) %>%
raster::crop(sf::st_transform(geom, sf::st_crs(r)), snap = "out") %>%
spex::qm_rasterToPolygons(na.rm = FALSE) %>%
dplyr::mutate(grid_id = 1:n())
}