Add longitude and latitude coordinates to an sf object
Source:R/spat_sf_add_coords.R
sf_add_coords.Rd
Add longitude and latitude coordinates as new columns to an sf object
(sf_object
). It extracts the coordinates from the sf object, converts them
into a tibble, and appends them to the original sf object as new columns. If
name_x
or name_y
, provided as arguments respectively, already exist in
the sf object, the function either 1) overwrites these columns if
overwrite
is set to TRUE
or 2) appends "_NEW" to the new column names to
avoid overwrite if overwrite
is set to FALSE
.
Arguments
- sf_object
An
sf
object to which longitude and latitude columns will be added.- name_x, name_y
Character. Name of the longitude column to be added. Defaults to
Long
andLat
.- overwrite
Logical. Whether to overwrite existing columns with names specified by
name_x
andname_y
. IfFALSE
and columns with these names exist, new columns are appended with "_NEW" suffix. Defaults toFALSE
.
Note
If the overwrite parameter is FALSE
(default) and columns with the
specified names already exist, the function will issue a warning and append
"_NEW" to the names of the new columns to avoid overwriting.
Examples
pt1 = sf::st_point(c(0,1))
pt2 = sf::st_point(c(1,1))
d = data.frame(a = c(1, 2))
d$geom = sf::st_sfc(pt1, pt2)
df = sf::st_as_sf(d)
df
#> Simple feature collection with 2 features and 1 field
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 0 ymin: 1 xmax: 1 ymax: 1
#> CRS: NA
#> a geom
#> 1 1 POINT (0 1)
#> 2 2 POINT (1 1)
(df <- sf_add_coords(df))
#> Simple feature collection with 2 features and 3 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 0 ymin: 1 xmax: 1 ymax: 1
#> CRS: NA
#> a Long Lat geom
#> 1 1 0 1 POINT (0 1)
#> 2 2 1 1 POINT (1 1)
(sf_add_coords(df))
#> Warning: Provided column names for longitude and Latitude already exist in the data; `_NEW` is used as suffix
#> Simple feature collection with 2 features and 5 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 0 ymin: 1 xmax: 1 ymax: 1
#> CRS: NA
#> a Long Lat Long_NEW Lat_NEW geom
#> 1 1 0 1 0 1 POINT (0 1)
#> 2 2 1 1 1 1 POINT (1 1)
(sf_add_coords(df, overwrite = TRUE))
#> Warning: Provided column names for longitude and Latitude already exist in the data; these columns were overwritten
#> Simple feature collection with 2 features and 3 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 0 ymin: 1 xmax: 1 ymax: 1
#> CRS: NA
#> a Long Lat geom
#> 1 1 0 1 POINT (0 1)
#> 2 2 1 1 POINT (1 1)