I am new to R and a new to programming. I have a shapefile which I have imported into R and found that it is a Spatial Polygons Data Frame. I want to use the crossdist function in spatstat but before that I am attempting to convert this into owin and then class psp as that is how I have read to address this issue. My problem is that I am not sure how to convert my data to owin. Any help on how to address this would be greatly appreciated. Thanks.
2 Answers
A SpatialPolygons or SpatialPolygonsDataFrame object represents a list of several distinct spatial regions, e.g. states of the USA, while an owin object represents a single spatial region (possibly consisting of several disjoint pieces), e.g. Hawaii.
To convert a SpatialPolygonsDataFrame (say x) to a list of owin objects:
y <- as(x, "SpatialPolygons")
p <- slot(y, "polygons")
v <- lapply(p, function(z) { SpatialPolygons(list(z)) }
winlist <- lapply(v, as.owin)
The result winlist is a list, each entry of which is an 'owin' object representing one of the polygonal regions in x.
For further information see the spatstat vignette on shapefiles: start R, load the spatstat package, type vignette('shapefiles') and view the section on SpatialPolygonsDataFrame objects.
For more detailed information, see the book on spatstat.
Comments
Not quite sure what you're looking for, but does this help?
setwd("<directory with shapefile>")
library(rgdal)
library(spatstat)
# polygon TIGER/Line shapefile of US States (Census Bureau)
US.States <- readOGR(dsn=".",layer="tl_2013_us_state")
# centroids of each state
centroids <- data.frame(coordinates(US.States))
# distance from every state to every other state
dist.matrix <- crossdist(centroids$X1,centroids$X2, centroids$X1,centroids$X2)
dist <- data.frame(State=US.States$NAME,dist.matrix)
colnames(dist)[-1] <- as.character(dist$State)
# dist[1:5,1:5]
# State West Virginia Florida Illinois Minnesota
# 1 West Virginia 0.000000 10.32684 8.662579 15.618328
# 2 Florida 10.326844 0.00000 13.422915 21.373925
# 3 Illinois 8.662579 13.42292 0.000000 8.015524
# 4 Minnesota 15.618328 21.37393 8.015524 0.000000
# 5 Maryland 3.938274 11.95297 12.516987 19.011532
The shapefile in this example can be found here.