Lenn
Lenn

Reputation: 1469

Create a sfc-column from nested lists in R

So the issue is that I have a column, "location", which is a list of lists. The nested lists are of length 2 and all have at index 1 the latitude-value and at index 2 the longitude-value of a point. As I want to create a sfc-object from this column, I thaught about converting each nested list into a sfg-object in order to convert it afterwards into a sfc-object.

The first three nested list look like this:

> geometry[1:3]
[[1]]
[1] 49.45082 11.07702

[[2]]
[1] 49.45006 11.07262

[[3]]
[1] 49.45704 11.08664

So I'm just a little stuck and don't know how to create a sfc-object from this nested list. Any hint would be awesome!!

Upvotes: 3

Views: 1451

Answers (1)

camille
camille

Reputation: 16832

If what you have is just a list of vectors with coordinates, you can use purrr::map or lapply to iterate over each and convert to a list of sf point objects, then convert that to an sfc.

library(dplyr)
library(sf)

coords <- list(
  c(49.45082, 11.07702),
  c(49.45006, 11.07262),
  c(49.45704, 11.08664)
)

purrr::map(coords, st_point) %>%
  st_as_sfc()
#> Geometry set for 3 features 
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: 49.45006 ymin: 11.07262 xmax: 49.45704 ymax: 11.08664
#> epsg (SRID):    NA
#> proj4string:    NA
#> POINT (49.45082 11.07702)
#> POINT (49.45006 11.07262)
#> POINT (49.45704 11.08664)

If you have the more common form of your geometry as a data frame column, you can do the same operation to that column:

dat <- tibble(geometry = coords)

dat %>%
  mutate(geometry = purrr::map(geometry, st_point) %>%
           st_as_sfc())
#> # A tibble: 3 x 1
#>              geometry
#>               <POINT>
#> 1 (49.45082 11.07702)
#> 2 (49.45006 11.07262)
#> 3 (49.45704 11.08664)

Or convert the whole thing to an sf data frame:

dat %>%
  mutate(geometry = purrr::map(geometry, st_point)) %>%
  st_as_sf()
#> Simple feature collection with 3 features and 0 fields
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: 49.45006 ymin: 11.07262 xmax: 49.45704 ymax: 11.08664
#> epsg (SRID):    NA
#> proj4string:    NA
#> # A tibble: 3 x 1
#>              geometry
#>               <POINT>
#> 1 (49.45082 11.07702)
#> 2 (49.45006 11.07262)
#> 3 (49.45704 11.08664)

The choice between these just depends on your use.

Upvotes: 3

Related Questions