问题
I am trying to analyze spatial density of gas station points using R. I need to create a buffer (circle) around the gas stations and count the number of gas stations within the buffer. I'll then need to play around with buffer distances to see what's a reasonable buffer to see something interesting. These are the files I am working with: https://dl.dropboxusercontent.com/u/45095175/sbc_gas.shp; https://dl.dropboxusercontent.com/u/45095175/sbc_gas.shx; https://dl.dropboxusercontent.com/u/45095175/sbc_gas.dbf
# Install packages
x <- c("ggmap", "rgdal", "rgeos", "maptools", "ks")
lapply(x, library, character.only = TRUE)
all <- readShapePoints("sbc_gas.shp")
all.df <- as(all, "data.frame")
locs <- subset(all.df, select = c("OBJECTID", "Latitude", "Longitude"))
head(locs) # a simple data frame with coordinates
coordinates(locs) <- c("Longitude", "Latitude") # set spatial coordinates
plot(locs)
Any help greatly appreciated!!
回答1:
We cannot use your data as provided because the .shp file alone is not enough. At minimum, you must also provide the .shx and the .dbf file to be able to load this data.
However, something that should work is to get the package geosphere
. It contains a function called distGeo
. You can use it to get the distance from each gas station to all other stations. From the distance matrix, you should be able to select all stations within a specified distance.
回答2:
I found an answer to my question: fivekm <- cbind(coordinates(locs), X=rowSums(distm (coordinates(locs)[,1:2], fun = distHaversine) / 1000 <= 5)) # number of points within 5 km
来源:https://stackoverflow.com/questions/42498344/create-buffer-around-spatial-point-data-in-r-and-count-how-many-points-are-in-th