Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created April 4, 2018 00:13
Show Gist options
  • Save ateucher/ac96ecf108943dfb497860265a0a647e to your computer and use it in GitHub Desktop.
Save ateucher/ac96ecf108943dfb497860265a0a647e to your computer and use it in GitHub Desktop.
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, proj.4 5.0.0
library(rmapshaper)
library(geojsonio)
#> 
#> Attaching package: 'geojsonio'
#> The following object is masked from 'package:base':
#> 
#>     pretty
library(spData)
#> To access larger datasets in this package, install the spDataLarge
#> package with: `install.packages('spDataLarge',
#> repos='https://nowosad.github.io/drat/', type='source'))`

data("us_states")

# The apply_mapshaper_commands() function can be used to call mapshaper commands 
# that haven't been implememnted as functions in the R package. You can see the 
# full list of available mapshaper commands here: 
# https://github.com/mbloch/mapshaper/wiki/Command-Reference

# First you have to convert the sf (or sp) object to geojson:
states_js <- geojson_json(us_states)

# Use the affine command: 
# Shift DC 5 degrees East and 1 degree South using the `shift` argument, 
# and make it 10 times bigger using the `scale` argument.
# Shift California 10 degrees West and rotate it 40 degrees anticlockwise.
# Then convert back to sf, and plot it:
states_shifted <- states_js %>% 
  apply_mapshaper_commands("-affine shift=5,-1 scale=10 where='NAME == \"District of Columbia\"'
                           -affine shift=-10,0 rotate=-40 where='NAME== \"California\"'", 
                           force_FC = TRUE) %>% 
  geojson_sf()
  
plot(states_shifted["NAME"], )

Created on 2018-04-03 by the reprex package (v0.2.0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment