Skip to contents

Add longitude and latitude coordinates as new columns to an sf object (Sf_Obj). 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 NameX or NameY, 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.

Usage

sf_add_coords(Sf_Obj, NameX = "Long", NameY = "Lat", Overwrite = FALSE)

Arguments

Sf_Obj

An sf object to which longitude and latitude columns will be added.

NameX, NameY

A string specifying the name of the longitude column to be added. Defaults to Long and Lat.

Overwrite

A logical value indicating whether to overwrite existing columns with names specified by NameX and NameY. If FALSE and columns with these names exist, new columns are appended with "_NEW" suffix. Defaults to FALSE.

Value

An sf object with added longitude and latitude columns.

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.

Author

Ahmed El-Gabbas

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)