Search code examples
rlistdplyrtibble

tibbles and lists - r wrangling dplyr


I am trying to convert a bunch of points to polygons.

I found a nice example of what I'm trying to accomplish here: Convert data frame containing coordinates of polygons to sf

I'd like to try their method, but I don't have the skills to go from:

# how I see the points after read_csv - simply 3 columns lon, lat, id
df<-tibble(
  lon = c(-119.036,-119.002,-119.010,-119.044,-119.036,-119.002,-118.968,-118.977,-119.010,-119.002),
  lat = c(23.097,23.105,23.136,23.128,23.097,23.105,23.112,23.143,23.136,23.105),
  id = c(1,1,1,1,1,2,2,2,2,2)
 )  

to:

# how i want the info organized to work off of stkoverflow eg linked above
df<-tibble::tribble(
  ~id,     ~geometry,
  "1",    list(c(-119.036,23.097), c(-119.002,23.105), c(-119.010,23.136), c(-119.044,23.128), c(-119.036,23.097)),
  "2",    list(c(-119.002,23.105),c(-118.968,23.112),c(-118.977,23.143), c(-119.010,23.136), c(-119.002,23.105))
)


If possible, I'd like to do with dplyr commands.


Solution

  • out <- df %>%
      group_by(id) %>%
      summarize(geometry = list(Map(c, lon, lat)))
    out
    # # A tibble: 2 × 2
    #      id geometry  
    #   <dbl> <list>    
    # 1     1 <list [5]>
    # 2     2 <list [5]>
    

    Comparison with your second frame (I named df2):

    str(out)
    # tibble [2 × 2] (S3: tbl_df/tbl/data.frame)
    #  $ id      : num [1:2] 1 2
    #  $ geometry:List of 2
    #   ..$ :List of 5
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   ..$ :List of 5
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    str(df2)
    # tibble [2 × 2] (S3: tbl_df/tbl/data.frame)
    #  $ id      : chr [1:2] "1" "2"
    #  $ geometry:List of 2
    #   ..$ :List of 5
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   ..$ :List of 5
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1
    #   .. ..$ : num [1:2] -119 23.1