Convert table of coordinate to shape file using R

2020-07-10 07:58发布

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.

标签: r shapefile
2条回答
Lonely孤独者°
2楼-- · 2020-07-10 08:45

After suggestion by @Matthew Plourde, I have used the function SpatialPointsDataFrame to convert the UMTcoor to a spatial dataframe. That solved my problem.

There are also small detail in writeOGR that wasn't correct in my original script, the dataframe in the 1st argument should not be put in double bracket.

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

filePath="https://dl.dropboxusercontent.com/u/549234/s1.csv"
UTMcoor=read.csv(file=filePath)
coordinates(UTMcoor)=~X+Y
proj4string(UTMcoor)=CRS("++proj=utm +zone=48") # set it to UTM
UTMcoor.df <- SpatialPointsDataFrame(UTMcoor, data.frame(id=1:length(UTMcoor)))
LLcoor<-spTransform(UTMcoor.df,CRS("+proj=longlat"))
LLcoor.df=SpatialPointsDataFrame(LLcoor, data.frame(id=1:length(LLcoor)))
writeOGR(LLcoor.df, dsn="c:/todel" ,layer="t1",driver="ESRI Shapefile")
writeSpatialShape(LLcoor.df, "t2")
查看更多
姐就是有狂的资本
3楼-- · 2020-07-10 08:54

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)))
查看更多
登录 后发表回答