JAG2024
JAG2024

Reputation: 4317

Create buffer around spatial data in R

I have a spatial dataset of shopping centers that I would like to create buffers around in R.

I think these packages will be useful:

require(maptools)
require(geosphere) 

I was able to do so for a set of coordinates, but not for spatial data. The code looks like this:

coordinates(locs) <- c("Longitude", "Latitude")  # set spatial  coordinates
fivekm <- cbind(coordinates(locs), X=rowSums(distm (coordinates(locs)[,1:2], fun = distHaversine) / 1000 <= 5)) # number of points within 5 km

But I don't know what function/package to use for a set of polygons. Can someone please advise on the function (or code) and I will go from there?

Thanks!

Upvotes: 4

Views: 15815

Answers (3)

Will Hore-Lacy
Will Hore-Lacy

Reputation: 151

The two previous post have covered the details but I thought it might be helpful to provide a workflow. This is assuming you have you are using points of lat and long. What is your original spatial data format?

  1. Convert your coordinates into a Spatial Points Dataframe SpatialPointsDataFrame and assign it a geographic CRS (proj4) that matches your coordinate data (probably WGS84)
  2. Change the projection to a local projected CRS with preferred units
  3. Apply buffer to spatial point data frame, the width will now be in more usable units

Upvotes: 0

S&#233;bastien Rochette
S&#233;bastien Rochette

Reputation: 6661

In library rgeos, there is the gBuffer function that works with SpatialPoints or SpatialPolygons.
The width parameter allows to set the distance to which you want to buffer. However, be careful, this distance is in the scale of the coordinates system used. Thus, in degrees and not in meters with non-projected data. As suggested by @Ege Rubak, you will have to project your data with spTransform first (be sure to use the appropriate CRS according to your location).
As for now, rgeos library works with library sp, but not (yet?) with the recent sf.

Upvotes: 4

Ege Rubak
Ege Rubak

Reputation: 4507

I think the only option at the moment is to project your longitude and latitude points to a flat map and then do everything there. As far as I know there are no packages for doing polygonal geometry on the sphere yet (I'm working on one, but there is no ETA).

Projection used to be done with spTransform from the sp package, but now it may be more convenient to use the more modern simple features package sf which has the function st_transform. The vignette https://cran.r-project.org/web/packages/sf/vignettes/sf1.html has a section called "Coordinate reference systems and transformations" to help you with this part. The buffering is described in the section "Geometrical operations".

Upvotes: 4

Related Questions