gIntersects and gIntersection
The rgeos library contains many tools for analyzing vector layers. The two most important functions are gIntersects and gIntersection. The function names are similar, but each returns something different.
We will use the two libraries rgdal and rgeos.
library(rgdal) library(rgeos)
Load the two vector layers railroad (black color) and road (brown color) using the tools of the rgdal library.
railroad <- readOGR("D:/", "railroad", stringsAsFactors = FALSE) road <- readOGR("D:/", "road", stringsAsFactors = FALSE)
The gIntersects function is used to display elements of a layer that intersect with objects of another layer.
int <- gIntersects(railroad,road)
> int [1] TRUE
The function defined in this way returns only the information whether the layers have common points (they intersect). If you add the argument byid, you get in the output a matrix containing information about intersecting elements between layers:
int <- gIntersects(railroad, road, byid = TRUE)
> int 0 1 2 3 4 .. 0 FALSE FALSE FALSE FALSE FALSE .. 1 FALSE FALSE FALSE FALSE FALSE .. 2 FALSE FALSE FALSE FALSE FALSE .. 3 FALSE FALSE FALSE FALSE FALSE .. 4 FALSE FALSE FALSE FALSE FALSE .. . .. .. .. .. ..
We can use the apply function to select road segments that intersect with railway lines:
sel <- apply(int, 1, any)
The selected sections are displayed in red in the variable sel in the map.
The function gIntersection creates a layer with intersections between two sets. In our case, these will be points (intersections) where roads intersect with railway lines.
intersections <- gIntersection(railroad, road)
The resulting layer will be the points marked with red dots on the map.
In summary:
gIntersects – used to check if elements/layers overlap each other.
gIntersection – used to create a layer of elements that are common to two sets.