Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert csv to shp in R

I have been trying for the past couple of days to convert a csv to shapefile. I know I can easily do in QGIS or Arc but would like to add this process into my existing R code.

So i can read in the csv with no issues

MyData <- read.csv(file="c:/TheDataIWantToReadIn.csv", header=TRUE, sep=",")

I found the code below from the Packages Shapefile help guide. However I can't seem to find a way for it to work on my code. My rows are each a point, therefore my shapefile I am trying to create will be all points. I don't have an Id column, however I do have x and y data in two separate columns.

dd <- data.frame(Id=c(1,2),X=c(3,5),Y=c(9,6))
ddTable <- data.frame(Id=c(1,2),Name=c("Item1","Item2"))
ddShapefile <- convert.to.shapefile(dd, ddTable, "Id", 1)
write.shapefile(ddShapefile, "c:/test", arcgis=T)

Any help would be greatly appreciated.

like image 709
Harmzy15 Avatar asked May 08 '15 15:05

Harmzy15


1 Answers

I would suggest using rgdal rather than shapefiles. In order to use rgdal, you'll have to check out the system requirements from http://cran.revolutionanalytics.com/web/packages/rgdal/.

The following code should get you in the right direction:

install.packages(c("rgdal", "sp"))
library(rgdal)
library(sp)
MyData <- read.csv(file="c:/TheDataIWantToReadIn.csv", header=TRUE, sep=",")

The following code snippet comes from Mapping in R using the ggplot2 package.

class(MyData) # data.frame
coordinates(MyData)<-~longitude+latitude # whatever the equivalent is in your 
# data.frame
class(MyData) # [1] "SpatialPointsDataFrame"
          # attr(,"package")
          # [1] "sp"

The following code snippet comes How to write a shapefile with projection - problem solved

writeOGR(crest.sp, "c:/test", "layer name", driver = "ESRI Shapefile")
like image 70
iembry Avatar answered Sep 30 '22 17:09

iembry