简体   繁体   中英

Convert lat and long dataframe to multiple spatial polygons in R

I have two problems I'm trying to solve, the first issue is the main one. Hopefully I've explained the second one decently.

1) My initial issue is trying to create spatial polygon dataframe from a tibble. For example, I have a tibble that outlines US states, from the urbnmapr library and I want to be able to plot spatial polygons for all 50 states. (Note: I already have made a map from these data in ggplot but I specifically want spatial polygons to plot and animate in leaflet):

> states <- urbnmapr::states
> states

# A tibble: 83,933 x 10
    long   lat order hole  piece group state_fips state_abbv state_name fips 
   <dbl> <dbl> <int> <lgl> <fct> <fct> <chr>      <chr>      <chr>      <chr>
 1 -88.5  31.9     1 FALSE 1     01.1  01         AL         Alabama    01   
 2 -88.5  31.9     2 FALSE 1     01.1  01         AL         Alabama    01   
 3 -88.5  31.9     3 FALSE 1     01.1  01         AL         Alabama    01  
...

2) Once I do this, I will want to join additional data from a separate tibble to the spatial polygons by the state name. What would be the best way to do that if I different data for each year? ie for the 50 states I have three years of data, so would I create 150 different polygons for the states across years or have 50 state polygons but have all the information in each to be able to make 3 different plots of all states for the different years?

I can propose you the following (unchecked because I don't have access to the urbnmapr package with my R version).

Problem 1

If you specifically want polygons, I think the best would be to join a dataframe to an object that comes from a shapefile.

If you still want to do it on your own, you need to do two things:

  1. Convert your tibble into a spatial object with a point geometry
  2. Aggregate points by state

sf package can do both. For the first step (the easy one), use sf_as_sf function.

library(sf)
states
states_spat <- states %>% st_as_sf(., coords = c("lon","lat"))

For the second step, you will need to aggregate geometries. I can propose you something that will give you a MULTIPOINT geometry, not polygons. To convert into polygons, you could find this thread to help

states_spat <- states_spat %>% group_by(state_name) %>% 
  dplyr::summarise(x = n())

Problem 2

That's a standard join based on a common attributes between your data and a spatial object (eg a state code). merge or *_join functions from dplyr work with sf data as they would do with tibbles . You have elements there

By the way, I think it is better for you to do that than creating your own polygons from a series of points.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM