Search code examples
rfor-loopcran

How to increase buffer size in R-function


i would like to implement a function in R which is able to increase the size of a buffer in a for-loop.

The overall-plan is to write a package, which uses a test- and a reference-shapefile. It should create a buffer around the reference shapefile and increases the size as long as necessary, to intersect the whole test-shapefile.

Therefore, i already wrote some code snippets to insert the shapefiles and create the first buffer:

require("rgeos")
require("rgdal")
l1=readOGR(dsn="C:/Maps", layer="osm_ms1")
l2=readOGR(dsn="C:/Maps", layer="osm_ms2")

proj4string(l2) = CRS("+init=epsg:31467")  ## DHDN / 3-degree Gauss-Kruger zone 3
l2buffer <- gBuffer(l2, width=0.001, capStyle="ROUND")

plot(l2buffer, col="black")
lines(l2, col="red")
lines(l1, col="blue")

Until now, every works fine. After that, i wanted to transfer this method to a for-loop with a buffer for every step:

i = 0.001

buffergrow = function(shape) {
  for (k in 1:10) {
    linebuffer[k] <- gBuffer(l2, width=i, capStyle="ROUND")
    plot(linebuffer[k])
    i = i+0.001
  }  
}

> buffergrow(l2)
Error in linebuffer[k] <- gBuffer(shape, width = i, capStyle = "ROUND") : 
  Object 'linebuffer' not found

As you can see, an error occurs when i call the function 'buffergrow' with 'l2' as the argument (shape). Does anybody has an idea why this happens? I tried already some other ideas, but i need some help.

Optionally / Additionally: Do you have some hints for me, regarding the further work for my overall plan?

Best regards, Stefan


Solution

  • You have to initialize an object before accessing its subelements. E.g.:

    foo <- double(10)
    for (i in 1:10) {
      foo[i] <- i;
    }
    # or
    linebuffer <- list()
    for (i in 1:10) {
      linebuffer[[i]] <- i;
    }
    

    But you don't need an object linebuffer in your usecase. Try the following instead:

    buffergrow = function(shape) {
      for (k in 1:10) {
        plot(gBuffer(l2, width=i, capStyle="ROUND"))
        i = i+0.001
      }  
    }
    

    EDIT: If you need to store the gBuffer results:

    buffergrow = function(shape) {
      i <- 1
      linebuffer <- vector("list", 10)
      for (k in 1:10) {
        linebuffer[[k]] <- gBuffer(l2, width=i, capStyle="ROUND")
        plot(linebuffer[[k]])
        i = i+0.001
      }  
      return(linebuffer)
    }