1

I have a map data whose format is rds. Now I want to use this data in another software which asks for shp format. How to convert rds format data into shp format in R?

Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
Yang Wang
  • 51
  • 6

1 Answers1

4

If it is spatial object saved as a R-specific binary file of "Serialization Interface for Single Objects" type (see ?readRDS) probably created at some point by saveRDS(), read your file with

library(rgdal)
library(sp)

x <- readRDS("path/to/the/rds_file.rds")

and then write it with:

rgdal::writeOGR(x, "path/to/destination", "filename", driver = "ESRI Shapefile")

Be sure not to put ".shp" at the end of your output filename.

Also be sure not to put a / at the end of the destination folder. Otherwise you might face the error

Creation of output file failed

When the error

Error: inherits(obj, "Spatial") is not TRUE

you might have forgotten the x as the first argument in the writeOGR function.

Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
loki
  • 7,753
  • 6
  • 46
  • 70
  • I successfully read the rds file but when I run the output code, there is the Error: inherits(obj, "Spatial") is not TRUE. Why? – Yang Wang Jul 21 '17 at 08:15
  • you probably forgot to put the object (in my example `x`) into the `writeOGR` function. Also see my edit for the needed libraries. – loki Jul 21 '17 at 08:23
  • I have installed two packages and put the x in my codes: '>library(rgdal) > library(sp) > a=readRDS('D:/data/chinamap/chinamap.rds') > rgdal::writeOGR(a, "D:/data/chinamap/", "china", driver = "ESRI Shapefile") ', but the error I said still appears. I am very confused. – Yang Wang Jul 21 '17 at 09:15
  • if this doesn't work either, could you please add the output of `class(a)` and `typeof(a)`? – loki Jul 21 '17 at 09:24
  • It doesn't work. The output of 'class(a)' is "data.frame", and the output of 'typeof(a)' is "list". Should I covert 'a' to another format? – Yang Wang Jul 22 '17 at 07:08
  • The problem here is that you have spaitial data in a quite non spatial format. Therefore, you have to transform it first into spatial objects. Look into `?SpatialPointsDataFrame()`, `?SpatialLinesDataFrame()` or `?SpatialPolygonsDataFrame()`. Also have a look at [this post](https://stackoverflow.com/a/29736844/3250126) to see how data frames can be converted into spatial data types. After you have `Spatial*DataFrame` object, the above solution will solve the rest. – loki Jul 22 '17 at 08:28