Convert matrix or data frame with point coordinates to a spatial (sf) object

locs2sf(locs, crs = 4326, lon.col = NULL, lat.col = NULL)

Arguments

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.

crs

A character string, number (EPSG value), or crs object specifying the coordinate reference system (see sf::st_crs() or https://spatialreference.org). Default is geographic (unprojected) coordinates, datum WGS84 (EPSG = 4326).

lon.col

Character (optional). Name of the column containing longitude data.

lat.col

Character (optional). Name of the column containing latitude data.

Value

An sf::sf() object.

Examples

locs <- matrix(runif(20), ncol = 2)
locs2sf(locs)
#> As locs is a matrix, assuming first two columns are longitude and latitude, respectively.
#> Simple feature collection with 10 features and 0 fields
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: 0.007399441 ymin: 0.03424133 xmax: 0.834333 ymax: 0.9755478
#> Geodetic CRS:  WGS 84
#>                         geometry
#> 1   POINT (0.08075014 0.8746007)
#> 2     POINT (0.834333 0.1749406)
#> 3   POINT (0.6007609 0.03424133)
#> 4    POINT (0.1572084 0.3203857)
#> 5  POINT (0.007399441 0.4023282)
#> 6    POINT (0.4663935 0.1956698)
#> 7    POINT (0.4977774 0.4035381)
#> 8   POINT (0.2897672 0.06366146)
#> 9     POINT (0.732882 0.3887013)
#> 10   POINT (0.7725215 0.9755478)

locs <- data.frame(species = rep("Laurus nobilis", 10), x = runif(10), y = runif(10))
locs2sf(locs)
#> Assuming 'y' is latitude
#> Assuming 'x' is longitude
#> Simple feature collection with 10 features and 1 field
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: 0.05144628 ymin: 0.03123033 xmax: 0.9805397 ymax: 0.9485766
#> Geodetic CRS:  WGS 84
#>           species                     geometry
#> 1  Laurus nobilis POINT (0.2898923 0.03123033)
#> 2  Laurus nobilis  POINT (0.6783804 0.2255625)
#> 3  Laurus nobilis  POINT (0.7353196 0.3008308)
#> 4  Laurus nobilis  POINT (0.1959567 0.6364656)
#> 5  Laurus nobilis  POINT (0.9805397 0.4790245)
#> 6  Laurus nobilis  POINT (0.7415215 0.4321713)
#> 7  Laurus nobilis POINT (0.05144628 0.7064338)
#> 8  Laurus nobilis  POINT (0.5302125 0.9485766)
#> 9  Laurus nobilis  POINT (0.6958239 0.1803388)
#> 10 Laurus nobilis   POINT (0.688556 0.2168999)