R/random_points.R

Defines functions random_points

Documented in random_points

#' Generate Random Points
#'
#' Generate n random points within a bounding box
#'
#' @param bbox a bounding box object generated by st_bbox
#' @param n_points the number of points to generate
#' @param seed optionally use set.seed to make the point reproducible
#' @return a sf object of points with the EPSG 27700
#' @import sf
#' @import dplyr
#' @importFrom magrittr %>%
#' @export random_points
random_points <-
  function(bbox, n_points, seed = NULL) {
    # Set the seed if specified
    if (!is.null(seed)) {
      set.seed(seed)
    }

    # use a uniform distributin to generate X and Y values within the bounding box
    # Could add an option for padding of the points so the dont intersect with the bounding box
    x <-
      bbox["xmin"] + ((bbox["xmax"] - bbox["xmin"]) * stats::runif(n_points))
    y <-
      bbox["ymin"] + ((bbox["ymax"] - bbox["ymin"]) * stats::runif(n_points))

    # Convert the x and y vectors into an sf object and specify the crs as 27700
    points <-
      dplyr::tibble(x = x, y = y) %>%
      sf::st_as_sf(coords = c("x", "y"), crs = 27700)

    # Could add functionality to transform the points to the crs of the input bbox
    return(points)
  }
MatthewJWhittle/spatialutils documentation built on March 16, 2023, 11:30 p.m.