# How to build polygons from buffered points and merge overlapping ones using R?

I have a sample of 3 groups of points which are similarly spread within their groups.

``````
> pts
x        y
[1,] 453067.5 364073.5
[2,] 453066.5 364072.5
[3,] 453068.5 364072.5
[4,] 453063.5 364071.5
[5,] 453065.5 364071.5
[6,] 453067.5 364071.5
[7,] 453069.5 364071.5
[8,] 453071.5 364071.5
[9,] 453062.5 364070.5
[10,] 453064.5 364070.5
[11,] 453067.5 364065.5
[12,] 453069.5 364065.5
[13,] 453071.5 364065.5
[14,] 453073.5 364065.5
[15,] 453075.5 364065.5
[16,] 453077.5 364065.5
[17,] 453079.5 364065.5
[18,] 453054.5 364064.5
[19,] 453056.5 364064.5
[20,] 453058.5 364064.5
``````

Then I can convert to `sp` object: `pts_sf = sf::st_as_sf(as.data.frame(pts), coords = c(1,2))`. Now trying to create buffer `pts_buf <- gBuffer(pts_sf, TRUE, 2)` but get error

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘is.projected’ for signature ‘"sf"’

Other way round, I can use buffer like this `pts_buf <- sf::st_buffer(pts_sf, 2)` but now I get error when trying `pts_uni <- rgeos::gIntersects(pts_buf, byid=TRUE, returnDense = FALSE)`

Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, func) :
rgeos_convert_R2geos: invalid R class, unable to convert

I use `pts_int = sf::st_intersects(pts_buf)` but this is not an object I need. Can I find any compatibilities to go out with it?

• If you found a solution, don't publish it as a part of your question but as an answer to your own question (and remove it from question). Jun 17, 2019 at 8:34
• The reason for your initial failure is because the functions from `sf` create objects that can't be read by functions in the `rgeos` package (like `gBuffer`). `rgeos` uses the earlier `sp` class objects. Jun 17, 2019 at 9:12
• agreed twice guys Jun 17, 2019 at 9:44

Found a solution using `sf` package:

So having a matrix of points, First I need sf object

``````pts_sf = sf::st_as_sf(as.data.frame(pts), coords = c(1,2))
``````

Next I can perform buffer

``````pts_buf <- sf::st_buffer(pts_sf, 2)
``````

then union

``````pts_com <- sf::st_union(pts_buf)
``````

and ath end I can get normal polygon from it

``````pts_pol <- sf::st_cast(pts_com, "POLYGON")
``````

This works well for larger data as well. Tested for up to 1M of points.