sf: Write Lat/Long from geometry into separate column and keep ID column

Solution using unlist + map()

library(tidyverse)

separated_coord <- df %>%
    mutate(long = unlist(map(df$geometry,1)),
           lat = unlist(map(df$geometry,2)))

separated_coord

A possible approach is to unlist it.

setNames(data.frame(df[[1]], 
                    matrix(unlist(df[2]), ncol=2, byrow=TRUE)), 
         c("ID", "lon", "lat"))

#   ID   lon  lat
# 1  1 117.2 31.8
# 2  2 116.4 40.1
# 3  4 117.9 26.0

Explanation

Data structure check with str(df) shows, that a variable - geometry - is in list format, which can be unhandy. A way to solve this is to unlist() it, transform it into a 2-column matrix, and reassemble it with the first column. With setNames() we are able to assign new column names in one step.


st_geometry can be used with dplyr::mutate:

library(magrittr) #for the pipe
df <- df %>%
  dplyr::mutate(lon = sf::st_coordinates(.)[,1],
                lat = sf::st_coordinates(.)[,2])

df
Simple feature collection with 3 features and 3 fields
geometry type:  POINT
dimension:      XY
bbox:           xmin: 116.4 ymin: 26 xmax: 117.9 ymax: 40.1
CRS:            EPSG:4326
# A tibble: 3 x 4
     ID     geometry   lon   lat
* <dbl>  <POINT [°]> <dbl> <dbl>
1     1 (117.2 31.8)  117.  31.8
2     2 (116.4 40.1)  116.  40.1
3     4   (117.9 26)  118.  26 

And if you no longer care about geometry, transform in a standard dataframe using df %>% sf::st_set_geometry(NULL)

Tags:

R

Sf