as_points: Convert two-dimensional locations to a spatially explicit...

View source: R/conversions.R

as_pointsR Documentation

Convert two-dimensional locations to a spatially explicit object

Description

Convert two-dimensional locations to a spatially explicit object

Usage

as_points(x, crs, to_class = c("sf", "sfc", "sp", "sv"))

Arguments

x

A numerical two-dimensional object (a matrix, array, or data.frame) with longitude/X, latitude/Y as columns; a sp::SpatialPoints object; or a terra::SpatVector object; or a sf object with a point geometry, i.e., an object with a class sf or sfc.

crs

An object which is a crs or from which one can be derived. x can be numeric as a EPSG number; a character string as a wkt; a character string as a proj4 (not recommended because outdated); or of a class including raster::Raster, sp::Spatial, sp::CRS, or a sf or sfc class.

to_class

A character string. Convert to "sp" for a sp::SpatialPoints object; to "sv" for a terra::SpatVector object; to "sf" for a sf object; or convert to "sfc" for a sf::sfc_POINT object.

Value

An object of the requested class.

Details

Argument crs is only used if x is not a spatial object with an embedded crs; the argument is otherwise ignored and should be missing.

Notes

This function does not carry out crs transformation.

Examples

locations <- matrix(
  data = c(-120.325, -111.245, 39.855, 36.753),
  nrow = 2
)

pts_sf1 <- as_points(locations, crs = 4326, to_class = "sf")
pts_sfc1 <- as_points(locations, crs = 4326, to_class = "sfc")
pts_sv1 <- as_points(locations, crs = 4326, to_class = "sv")

pts_sf2 <- as_points(pts_sv1, to_class = "sf")
pts_sfc2 <- as_points(pts_sv1, to_class = "sfc")
pts_sv2 <- as_points(pts_sf1, to_class = "sv")

all.equal(pts_sf1, pts_sf2, check.attributes = FALSE)
all.equal(pts_sfc1, pts_sfc2, check.attributes = FALSE)
all.equal(pts_sv1, pts_sv2)
all.equal(locations, sf::st_coordinates(pts_sf1), check.attributes = FALSE)
all.equal(locations, sf::st_coordinates(pts_sfc1), check.attributes = FALSE)
all.equal(locations, terra::crds(pts_sv1), check.attributes = FALSE)

if (requireNamespace("sp")) {
  pts_sp1 <- as_points(locations, crs = 4326, to_class = "sp")
  pts_sp2 <- as_points(pts_sf1, to_class = "sp")
  all.equal(pts_sp1, pts_sp2)
  all.equal(locations, sp::coordinates(pts_sp1), check.attributes = FALSE)
}

# A vector of length two is interpreted as a single point location
pts_sf11 <- as_points(locations[1, ], crs = 4326, to_class = "sf")

DrylandEcology/rSW2st documentation built on Jan. 10, 2024, 6:22 p.m.