extend (buffer) boundary of shape file in R

1.2k views Asked by At

I need to extend the boundary of a field (only boundary) by x meters. I tried using gBuffer from rgeos R package - output of the transformation gives me only boundary of the field and rest polygons inside the field are lost with data.

How I can use gBuffer / any other way to extend only boundary of spatial polygon object (shape file) by 10m and keeping everything intact (inside polygons and data)

Tried Code -

field <- raster::shapefile("test.shp")
class(field)
plot(field)
View(field@data)

field  <- sp::spTransform(field,CRS("+init=epsg:32632"))
plot(field)

field10m  <- rgeos::gBuffer(field , width = 10)
plot(field10m)

Test shapefile can be downloaded from here https://drive.google.com/file/d/1s4NAinDeBow95hxr6gELHHkhwiR3z6Z9/view?usp=sharing

1

There are 1 answers

2
Jindra Lacko On

I suggest you consider a workflow based on the {sf} package; it makes for a bit clearer code than sp and rgeos (it will use the same geometry engine, but hide the gritty parts under the hood).

The code preserves all data features (actually, only one - a column named Rx) of your shapefile.

Note that since the yellow element / Rx = 120 / consists of multiple polygons each of them is buffered, resulting in overlaid features. This is expected outcome.

Should this be undesired behavior you can consider using a dplyr::group_by(Rx) followed by dplyr::summarise() to dissolve the internal boundary lines before applying the sf::st_buffer() call.

library(sf)
library(dplyr)
library(mapview) # needed only for the final overview
library(leafsync) # dtto.

test_map <- sf::st_read("./Map/test.shp")

# find an appropriate projected metric CRS
crsuggest::suggest_crs(test_map, type = "projected")

result <- test_map %>% 
  sf::st_transform(5683) %>%  # transform to a metric CRS
  sf::st_buffer(10) # buffer by 10 meters

# a visual check / note how the polygons are overlaid
leafsync::latticeview(mapview::mapview(test_map),
                      mapview::mapview(result))

two maps from code above; alongside