2
votes

How to buffer SpatialPolygons in a SpatialPolygonsDataFrame with specific widths for each SpatialPolygon taken from its attributes.

Following example is code is taken from SpatialPolygons - Creating a set of polygons in R from coordinates and slightly modified:

square <- t(replicate(50, {
  o <- runif(2)
  c(o, o + c(0, 0.1), o + 0.1, o + c(0.1, 0), o)
}))
ID <- paste0('sq', seq_len(nrow(square)))

# Create SP
polys <- SpatialPolygons(mapply(function(poly, id) {
  xy <- matrix(poly, ncol=2, byrow=TRUE)
  Polygons(list(Polygon(xy)), ID=id)
}, split(square, row(square)), ID))

# Create SPDF
polys.df <- (polys, data.frame(id=ID, row.names=ID))
polys.df$radius <- runif(50, 2.0, 8)

> head(polys.df)
      radius
sq1 7.397579
sq2 5.123130
sq3 4.607719
sq4 4.052619
sq5 6.571260
sq6 3.912436

Each SpatialPolygon should be buffered with the value of its column "radius".

Trying following loop results in only one SpatialPolygon as output

for (i in length(polys.df)) {
  polys.df.buffer <- gBuffer(polys.df[i,], width=polys.df$radius[i])
}

Following loop returns all Polygons buffered with the same buffer width, but not with the defined buffer width for each Polygon specified in the column "radius":

for (i in length(CrownsOut)) {
  polys.df.buffer <- gBuffer(polys.df[ ], width=polys.df$radius[i], byid=TRUE)
}
1
I think you're missing a call to SpatialPolygonsDataFrame for polys.dfSeGa
could you precise that or give a sample code?N'ya
In your code you have polys.df <- (polys, data.frame(id=ID, row.names=ID)), but it must be SpatialPolygonsDataFrame(polys, data.frame(id=ID, row.names=ID))SeGa

1 Answers

2
votes

The code was almost correct. You need to initialize a list before the for loop and assign in each iteration the buffered Polygon. You also need to add 1:length(polys.df) in the loop condition, otherwise it will only take the last polygon and you need to assign an ID for every polygon.

library(rgeos)

spList = vector("list", length(polys.df))
for (i in 1:length(polys.df)) {
  a <- gBuffer(polys.df[i,], width = polys.df$radius[i])
  a$id = i
  spList[[i]] <- a
}

spListAll <- do.call("rbind", spList)

plot(spListAll)