R/split_bbox.R

Defines functions split_bbox

Documented in split_bbox

#' Split Bounding Box
#'
#' Split a bounding box into an equal number of squares
#' @param bbox a bounding_box created by sf::st_bbox()
#' @param n_x the number of boxes on the x axes
#' @param n_y the number of boxes on the y axis
#' @return a list of bounding boxs generated by sf::st_bbox()
#' @import dplyr
#' @importFrom tidyr expand_grid
#' @importFrom magrittr %>%
#' @import sf
#' @importFrom purrr map

split_bbox <- function(bbox, n_x = 2, n_y = 2) {
  # Assert that bbox is a bounding box
  stopifnot(class(bbox) %in% "bbox")

  # Get the length of the x axis
  x_ext <- bbox["xmax"] - bbox["xmin"]
  # Get the length of the y axis
  y_ext <- bbox["ymax"] - bbox["ymin"]

  incr_x <- x_ext / n_x
  incr_y <- y_ext / n_y

  # Create a sequence of x and y coordinates to generate the xmins and ymins
  xmin <- seq(from = bbox["xmin"], to = bbox["xmax"], by = incr_x)
  ymin <- seq(from = bbox["ymin"], to = bbox["ymax"], by = incr_y)

  # Remove the last element of x and y to ensure that the
  # top right corner isnt create an xmin or ymin
  xmin <- xmin[1:length(xmin) - 1]
  ymin <- ymin[1:length(ymin) - 1]

  bbox_table <-
    expand_grid(xmin, ymin) %>%
    mutate(xmax = xmin + incr_x,
           ymax = ymin + incr_y)

  bounding_boxes <-
    transpose(bbox_table) %>% map( ~ .x %>%
                                     unlist %>% st_bbox(crs = st_crs(bbox)$epsg))

  return(bounding_boxes)
}
MatthewJWhittle/spatialutils documentation built on March 16, 2023, 11:30 p.m.