Reputation: 726
I am very new to programming in R and I am trying to plot data from a SpatialLinesDataFrame. Plotting all of the data is as easy as saying plot(my.SpatialDataFrame)
, however what I want to do is plot small sections of the data near to certain points.
The data looks something like this:
[[2]]
An object of class "Lines"
Slot "Lines":
[[1]]
An object of class "Line"
Slot "coords":
[,1][,2]
[1,] x y
[2,] x y
[3,] x y
[4,] x y
[5,] x y
Slot "ID":
[1] "1"
[[3]]
An object of class "Lines"
Slot "Lines":
[[1]]
An object of class "Line"
Slot "coords":
[,1][,2]
[1,] x y
[2,] x y
[3,] x y
[4,] x y
Slot "ID":
[1] "2"
There are an arbitrary number of coordinates in each Line object. What I have been trying to do is use vectorised operations such as ifelse
to identify which lines start near to some coordinate of my choice and remove the objects from the spatial data frame that do not. However I have been unable to get that to work as I am struggling with being new to R syntax and the SpatialLinesDataFrame in particular. Is my approach correct? How would I go about implementing it? I also tried to use apply and lapply but those didnt seem like they would work.
Please let me know if I need to supply any additional information.
Upvotes: 0
Views: 736
Reputation: 726
As Paul mentioned above I was able to do this by creating a rectangular SpatialPolygon and the using the gIntersection
function from the rgeos
package I was able to get only the points within the desired rectangle.
#libraries
library(sp) #for the spatialLinesDataFrame class
library(rgeos) #for the gIntersection function
# WGS84 long/lat coordinate system
wgs.84 <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
#create the bounding box based on the dimensions required
spatialBoundingBox <- SpatialPolygons( list( Polygons( list( Polygon( rbind( c( minX, minY), c( maxX, minY), c( maxX, maxY), c(minX , maxY)), hole = FALSE)), ID = c('1'))), proj4string = CRS( wgs.84))
#calculate the intersection of the bounding box and the data - this will return the same type as my.data
my.data.subset <- gIntersection(spatialBoundingBox, my.data)
#plot the original data and the subset on the same plot showing the difference
plot(my.data)
lines(my.data.subset, col="green")
Upvotes: 3