How to create several buffers around points of a simple feature in a loop?

I have sample data representing 2 points (sf). I want to create buffers with the width 2, 1 and 0.5. My approach is the below. Is there any way to do this in more efficient way? How can I wrap this process up in a loop?

library(sf)

g = st_sfc(c(st_point(1:2),st_point(3:2)))

g.2 <- st_buffer(g,2)
g.1 <- st_buffer(g,1)
g.05 <- st_buffer(g,0.5)

plot(st_geometry(g.2))
plot(st_geometry(g.1), add=TRUE)
plot(st_geometry(g.05), add=TRUE)
plot(st_geometry(g), add=TRUE)

2 answers

  • answered 2020-02-19 13:14 jazzurro

    I tried the following. I created a loop with map() in the purrr package and created three objects in a list. Then, I drew the first circle and added more circles in a for loop.

    library(purrr)
    library(sf)
    
    g <- st_sfc(c(st_point(1:2),st_point(3:2)))
    
    purrr::map(.x = c(0.5, 1, 2),
               .f = function(x){st_buffer(g, x)}) -> foo
    
    plot(st_geometry(foo[[1]]), xlim = c(0, 4), ylim = c(0, 4))
    
    for(i in 2:length(foo)) {plot(st_geometry(foo[[i]]), add = TRUE)}
    

    enter image description here

  • answered 2020-02-19 16:36 dieghernan

    Sticking to your request (using a loop) see here an example

    library(sf)
    g = st_sfc(c(st_point(1:2),st_point(3:2)))
    #Buffers
    buffers=c(2,1,0.5)
    #Initialise result
    result=g
    #Loop
    for (i in buffers){
      #Appending buffered points
      result=c(result,st_buffer(g,i))
    }
    #Remove initial element
    result=result[-1]
    plot(result, axes=TRUE)
    

    enter image description here