Search code examples
rgisshapefiler-leaflettigris

simplify my us state shapefile with rmapshaper::ms_simplify gives error


I'm making chloropleth us state map on my shiny app using leaflet package. I found rendering the map is very slow. After googling , it seems like maybe the shapefile is too complex and simplifying that might make it a lot faster. According to this post, simplifying the shapefile might be the answer.

Reading shape file works OK. I was able to render my leaflet map.

states_shape <- tigris::states(cb = TRUE, resolution='500k')
leaflet(states_shape) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = "white",
              color = "black",
              weight = 0.5) %>%
  setView(-98.5795, 39.8282, zoom=3)

I tried to simplify my shapefile with rmapshaper::ms_simplify

states_shape_simple <- rmapshaper::ms_simplify(states_shape, keep = 0.05, keep_shapes = TRUE)

I got error like below:

Error in FUN(X[[i]], ...) : isTRUE(gpclibPermitStatus()) is not TRUE

I have no idea what that mean and what to do. Does anyone know why that happened and how to make it work? Thanks a lot!


Solution

  • The following should work:

    # packages
    library(sf)
    #> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
    library(leaflet)
    
    # data
    states_shape <- tigris::states(cb = TRUE, resolution='500k', class = "sf")
    
    # simplify
    states_shape_simple <- rmapshaper::ms_simplify(states_shape, keep = 0.05, keep_shapes = TRUE)
    states_shape_simple <- st_transform(states_shape_simple, 4326)
    
    # plot
    leaflet(states_shape_simple) %>%
      addProviderTiles("CartoDB.Positron") %>%
      addPolygons(fillColor = "white",
                  color = "black",
                  weight = 0.5) %>%
      setView(-98.5795, 39.8282, zoom = 3)
    

    Created on 2020-05-27 by the reprex package (v0.3.0)

    I added states_shape_simple <- st_transform(states_shape_simple, 4326) since I received a warning message by leaflet saying that the object states_shape_simple had an invalid datum. I don't know if you face the same warning message.

    Anyway if you want to read something about the differences between sf and sp check Chapter 1 of Geoocomputation with R (and maybe Chapter 6 about reprojections, such as st_transform). I don't know why it fails with sp, maybe you can ask to the package mantainer.