【问题标题】:How to create several buffers around points of a simple feature in a loop?如何在循环中围绕简单特征的点创建多个缓冲区?
【发布时间】:2020-02-19 11:55:26
【问题描述】:

我有代表 2 个点 (sf) 的样本数据。我想创建宽度为 2、1 和 0.5 的缓冲区。我的方法如下。有没有办法以更有效的方式做到这一点?我怎样才能将这个过程包裹在一个循环中?

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)

【问题讨论】:

    标签: r loops buffer sf


    【解决方案1】:

    我尝试了以下方法。我在 purrr 包中使用map() 创建了一个循环,并在列表中创建了三个对象。然后,我画了第一个圆圈,并在 for 循环中添加了更多圆圈。

    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)}
    

    【讨论】:

      【解决方案2】:

      坚持您的要求(使用循环)请参阅此处的示例

      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)
      

      【讨论】:

        【解决方案3】:

        如果你对感兴趣,我主要根据做了以下,依托map*功能。在这种情况下,绘图是使用 制作的,并在gg 对象中生成三个绘图。

        library(sf)
        library(tidyverse)
        
        g <- st_sfc(c(st_point(1:2),st_point(3:2)))
        
        buffers <- c(0.5, 1, 2)
        
        x <- map2(buffers, g, function(buf, points){
        
          points %>% 
            st_buffer(., buf)
        
        }) %>% 
          set_names(., nm = sprintf("g.%s", buffers))
        
        gg <- map(names(x), function(y){
          z <- x[[y]]
        
          z %>% 
            ggplot(.) + 
            geom_sf() + 
            labs(title = y)
        
        }) 
        

        reprex package (v0.3.0) 于 2020-02-20 创建

        【讨论】:

          猜你喜欢
          • 2012-01-03
          • 2017-07-18
          • 2020-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-04
          相关资源
          最近更新 更多