saving shapefiles with R that can be re-read as a shapefile

I'm not totally clear on what format you need to save your spatial data frame in, but the simplest thing to do if you just want to save it disk as a file that R can read back in is to use the native .rds format, which can store any R object.

Here is an example where I read in a .shp file, add a new column, save it to disk, and then read it back in. (As an aside, I'm using the sf package, which I highly recommend for working with spatial data in R instead of sp. But this same pattern would work just as well for an sp object too!)

library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.1.3, PROJ 4.9.3

# read in .shp file to sf object
nc <- read_sf(system.file("shape/nc.shp", package = "sf"))

# add column to sf object
nc_new <- nc %>% 
  mutate(new_data = runif(nrow(nc)))

# save new object as .rds file
write_rds(nc_new, path = file.path(tempdir(), "nc_new.rds"))

# read in saved .rds
nc_saved <- read_rds(file.path(tempdir(), "nc_new.rds"))

# they match!
identical(nc_new, nc_saved)
#> [1] TRUE

Created on 2019-06-08 by the reprex package (v0.3.0)

2 Likes