Convert table of coordinate to shape file using R

anh.hv picture anh.hv · May 21, 2014 · Viewed 10.6k times · Source

I have a dataset of point coordinate in UTM zone 48.

  x           y       
615028.3  2261614    
615016.3  2261635    
614994.4  2261652    

The CSV file here.

I would like to load the CSV and create shapefile using R. My code is:

library(maptools)
library(rgdal)
library(sp)

    UTMcoor=read.csv(file="https://dl.dropboxusercontent.com/u/549234/s1.csv")
    coordinates(UTMcoor)=~X+Y
    proj4string(UTMcoor)=CRS("++proj=utm +zone=48") # set it to UTM
    LLcoor<-spTransform(UTMcoor,CRS("+proj=longlat")) #set it to Lat Long
    plot(LLcoor)
    points(LLcoor$X,LLcoor$Y,pch=19,col="blue",cex=0.8) #to test if coordinate can be plot as point map
    writeOGR(UTMcoor, dsn="c:/todel" ,layer="tsb",driver="ESRI Shapefile")
    writeSpatialShape("LLcoor","test")

In the last command (writeSpatialShape) R give the following error:

Error in writeSpatialShape("LL2", "test") : 
  x is acharacterobject, not a compatible Spatial*DataFrame

As I read the LLcoor from the console it seem that it already a Spatial DataFrame. Writing shape file using writeOGR (RGdal package) also give similar error. Any hint is much appreciated.

Answer

Matthew Plourde picture Matthew Plourde · May 21, 2014

There's something wrong with your example. The second to last line fails, too.

In any case, your error is pretty clear. You're supplying the name of the variable "LL2" instead of the variable itself. But in your example neither LLcoor nor UTMcoor are in the proper format to use with writeOGR or writeSpatialShape. You need to first convert them to SpatialDataframe, e.g., :

UTMcoor.df <- SpatialPointsDataFrame(UTMcoor, data.frame(id=1:length(UTMcoor)))