R/locs2vect.R

Defines functions locs2vect

Documented in locs2vect

#' Convert matrix or data frame with point coordinates to a SpatVector object
#'
#' @param locs A matrix or data frame containing point coordinates data.
#' If a matrix, the first two columns will be assumed to contain longitude
#'  and latitude coordinates, respectively.
#' If a data frame, the function will try to guess the columns containing the coordinates
#' based on column names, unless `lon.col` and `lat.col` are provided.
#' @param crs A number specifying the EPSG code (see <https://spatialreference.org>).
#' Default is geographic (unprojected) coordinates, datum WGS84 (EPSG = 4326).
#' @param lon.col Character (optional). Name of the column containing longitude data.
#' @param lat.col Character (optional). Name of the column containing latitude data.
#' @return A [terra::SpatVector()] object.
#' @export
#'
#' @examples
#' locs <- matrix(runif(20), ncol = 2)
#' locs2vect(locs)
#'
#' locs <- data.frame(species = rep("Laurus nobilis", 10), x = runif(10), y = runif(10))
#' locs2vect(locs)

locs2vect <- function(locs, crs = 4326, lon.col = NULL, lat.col = NULL) {

  if (!inherits(locs, c("matrix", "data.frame"))) stop("locs must be a matrix or data.frame")

  if (ncol(locs) < 2) stop("locs must be a matrix or dataframe with at least 2 columns.")

  if (is.matrix(locs)) {
    message("As locs is a matrix, assuming first two columns are longitude and latitude, respectively.")
    locs <- as.data.frame(locs)
    names(locs)[1:2] <- c("lon", "lat")
  }

  if (ncol(locs) > 1){
    n.orig <- nrow(locs)
    # This version adapted from mapr::occ2sp
    locs <- guess_latlon(locs, lat = lat.col, lon = lon.col)    # guess columns with coordinate data
    locs <- locs[!is.na(locs$longitude) & !is.na(locs$latitude), ]  # omit cases without coordinates
    n.nona <- nrow(locs)
    if (n.orig > n.nona) {
      warning("Some rows missing coordinates have been excluded.")
    }
    crs.terra <- paste0("epsg:", crs)
    locs.vect <- terra::vect(locs, geom = c("longitude", "latitude"), crs = crs.terra)
    return(locs.vect)
  }

}
Pakillo/rSDM documentation built on March 1, 2025, 12:30 a.m.