Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R/GIS: How to subset a shapefile by a lat-long bounding box?

Tags:

r

gis

I want to subset out a shapefile (the .shp and associated files are here) into another one bounded by a set of coordinates, say between longs [80,90] and lats [20,30], and then write this out as another shapefile. If I use the maptools package:

df = readShapeLines("/path/asia_rivers.shp")

and then look at the structure of the file with as.data.frame(df), I can't find any obvious way of subsetting by coordinates. I can use the PBSmapping package to subset:

df = importShapefile("/path/asia_rivers.shp")
df_sub = subset(df, X>=80 & X<=90 & Y >=20 & Y <=30)

but then I can't seem to be able to coerce this into a SpatialLines data frame which can be exported via writeSpatialShape() in maptools. I keep getting this error: Error in PolySet2SpatialLines(df_sub) : unknown coordinate reference system. Surely I am missing something very basic and there should be an easy way of subsetting geo-data by geo-coordinates?

like image 298
user702432 Avatar asked Mar 22 '12 15:03

user702432


People also ask

How do you subset a shapefile?

There are two methods you can use. One is to select a portion of an existing shape file and export that to a new shape file. The other is to clip an existing shape file by using another polygon shape file (like using a cookie cutter) to create a new shape file.

How do I create a shapefile in R?

To write out a shapefile from simple R data, you need to run convert.to. shapefile . The inputs to this function are a simple data frame of points (for points, polyLines, or polygons) and a data frame representing the dbf file.


1 Answers

You could try the following:

library(rgeos)
rivers <- readWKT("MULTILINESTRING((15 5, 1 20, 200 25), (-5 -8,-10 -8,-15 -4), (0 10,100 5,20 230))")
bbx <- readWKT("POLYGON((0 40, 20 40, 20 0, 0 0, 0 40))") 

rivers.cut <- gIntersection(rivers, bbx)

plot(rivers, col="grey")
plot(bbx, add=T, lty=2)
plot(rivers.cut, add=T, col="blue")
like image 179
johannes Avatar answered Nov 12 '22 04:11

johannes