Spatial relations

The following makes use of the sf package. You may need to install it from CRAN using the code install.packages("sf") if you want to run this on your computer. (The package is already installed on the notebook container, however.)

library(sf)
Linking to GEOS 3.9.0, GDAL 3.2.2, PROJ 7.2.1; sf_use_s2() is TRUE

The file "south-america-1990.RData" loaded below was created in a previous example was created in a previous example.

load("south-america-1990.RData")
plot_g <- function(x,...) plot(st_geometry(x),...)
plot_g(Brazil)
plot_g(Brasilia,add=TRUE,pch=19) # Circle
plot_g(Bogota,add=TRUE,pch=15) # Square
spatial-relations_5_0.png
st_contains(Brazil,Brasilia,sparse=FALSE)
     [,1]
[1,] TRUE
st_contains(Brazil,Bogota,sparse=FALSE)
      [,1]
[1,] FALSE
load("cshapes-1990.RData")
ThreeCountries <-
    subset(cshapes.1990,
           CNTRY_NAME %in% c("Brazil","Chile","Colombia"))
rownames(ThreeCountries) <- ThreeCountries$CNTRY_NAME
ThreeCapitals <-
    subset(cshapes.capitals.1990,
           CNTRY_NAME %in% c("Brazil","Chile","Colombia"))
rownames(ThreeCapitals) <- ThreeCapitals$CAPNAME
plot_g(ThreeCountries)
plot_g(ThreeCapitals,add=TRUE,pch=19)
spatial-relations_10_0.png
st_contains(ThreeCountries,ThreeCapitals,sparse=FALSE)
      [,1]  [,2]  [,3]
[1,]  TRUE FALSE FALSE
[2,] FALSE  TRUE FALSE
[3,] FALSE FALSE  TRUE
structure(
   st_contains(ThreeCountries,ThreeCapitals,sparse=FALSE),
   dimnames=list(rownames(ThreeCountries),rownames(ThreeCapitals))
)
         Brasilia Santiago Bogota
Brazil       TRUE    FALSE  FALSE
Chile       FALSE     TRUE  FALSE
Colombia    FALSE    FALSE   TRUE
st_touches(Brazil,Colombia,sparse=FALSE)
     [,1]
[1,] TRUE
st_touches(Brazil,Chile,sparse=FALSE)
      [,1]
[1,] FALSE
structure(
   st_touches(ThreeCountries,sparse=FALSE),
   dimnames=list(rownames(ThreeCountries),rownames(ThreeCountries))
)
         Brazil Chile Colombia
Brazil    FALSE FALSE     TRUE
Chile     FALSE FALSE    FALSE
Colombia   TRUE FALSE    FALSE
save(ThreeCountries,ThreeCapitals,file="three-countries.RData")