0

I need to rbind, in a loop, a load of SpatialPolygonDataFrames . These are created by buffering a roads file. However as my 'roads' file of class SpatialLinesDataFrame is 15000 rows long, the rbind function gets progressively slower. If they were data frames I would use rblindlist to speed things up. But that doesn't work with sp objects (right?). Does anyone have a good idea?

for (i in 1:nrow(roads)) {

  temp <- gDifference(gBuffer(roads[i,], byid = T, width =  15, capStyle = 'ROUND'), 
                  gBuffer(roads[i,], byid = T, width =  10, capStyle = 'ROUND'))

  slot(slot(temp, "polygons")[[1]], "ID") <- as.character(roads[i,]$oid)

  if (i == 1) {difference <- temp}

  if (i > 1) {difference <- rbind(difference, temp)}

  rm(temp)
  print(i)

}

Thanks

James

TheRealJimShady
  • 777
  • 3
  • 9
  • 24
  • Have you tried putting them into a list and doing `do.call(rbind, ListofSPDFs)` after the loop? – Roland May 16 '18 at 09:20
  • Hi Roland. I haven't . I will try that later. Though I like Tim's suggestion below so would like to pursue that first. Cheers again. – TheRealJimShady May 16 '18 at 10:53

1 Answers1

1

I am not sure you need to loop at all. You could use package sf. Here's an example of what (I think) you want to achieve:

library(mapview) # for the example lines data
library(sf)
trails$diff = st_geometry(st_buffer(trails, dist = 1500)) / st_geometry(st_buffer(trails, 1000))
mapview(trails$diff)

Is this your desired outcome? If not, you might want to provide an reproducible example.

TimSalabim
  • 5,604
  • 1
  • 25
  • 36
  • Hi TimSalabim . Thanks for the answer. That looks really promising .... but doesn't actually work for me? I get the below error. "Error in Ops.sfc(st_geometry(st_buffer(trails, dist = 1500)), st_geometry(st_buffer(trails, : operation / not supported" I thought maybe it needs wrapping in st_difference ? But struggle with that too. – TheRealJimShady May 16 '18 at 10:51
  • I thnk you need sf version 0.6.2 (latest CRAN) for that to work. See also [here](https://github.com/r-spatial/sf/issues/675) for some further info – TimSalabim May 16 '18 at 10:56
  • Wow, amazing, thanks Tim. This has saved me LOADS of time. – TheRealJimShady May 16 '18 at 11:49
  • `sf` really changed the way I approach spatial analyses. It is such a pleasant experience working with it and the API is well thought out in my opinion. – TimSalabim May 16 '18 at 12:53
  • Yes, I agree, it's just taking some adjustment from my years of working with sp and PostGIS databases. – TheRealJimShady May 16 '18 at 13:28
  • PS: If you've got a minute, you'll likely be able to help me with this one too: https://stackoverflow.com/questions/50372533/changing-crs-of-a-sf-object – TheRealJimShady May 16 '18 at 13:42
  • I've added a comment over there – TimSalabim May 16 '18 at 13:53