R/poly_grid.R

Defines functions poly_grid

Documented in poly_grid

#' Create grid of points within polygons
#'
#' @param x A sf polygon object.
#' @param cellsize Target cells size in meters.
#' @param ... Arguments passed on to st_make_grid.
#'
#' @return A sf object of points representing samples within input polygons.
#' @export

poly_grid <- function(x, cellsize, ...) {

  data <- sf::st_set_geometry(x, NULL) %>% split(seq(nrow(.)))

  in_crs <- st_crs(x)
  processing_crs <- in_crs

  if(st_is_longlat(x)) {
    x <- st_transform(x, 3857)
    processing_crs <- st_crs(x)
  }

  points <- purrr::map(st_geometry(x), function(geometry){

    st_make_grid(geometry, cellsize = cellsize, what = "centers", ...) %>%
      st_intersection(geometry)

  })

  data_points <- purrr::map2(points, data, function(points, data) {
    cbind(points, data)
  })


  out <- do.call(rbind, data_points) %>% sf::st_as_sf(crs= processing_crs)

  if (processing_crs != in_crs) {
    out <- st_transform(out, in_crs)
  }

  rownames(out) <- NULL
  return(out)


}
juoe/spatialtoolbox documentation built on May 7, 2019, 9:37 a.m.