1

I have a big list of SpatialPolygonsDataFrame objects I created using lapply and gdal_polygonizeR (code here: https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/) on a list of RasterLayer objects. I now want to union the boundaries of the polygon parts that touch within each SpatialPolygonsDataFrame using unionSpatialPolygons (maptools). I have tested this by calling an individual SpatialPolygonsDataFrame object, and it seems to work. But, when I try to do it for the list of all SpatialPolygonsDataFrame using lapply, I get an error. See code below (very sorry my example is not reproducible) and please provide a solution using lapply or alternative. Thanks

#convert RasterLayers to SpatialPolygonsDataFrame objects
polyl <- lapply(rastl, gdal_polygonizeR)

#test union of polygon parts within individual SpatialPolygonsDataFrame
tmp = unionSpatialPolygons(polyl[[10]], polyl[[10]]$DN) 

polyl[[10]]  #n = 360 features
tmp          #n = 8 features

#run union on all SpatialPolygonsDataFrame in list
polyl_union <- lapply(polyl, unionSpatialPolygons, SpP = 
polyl, IDs = polyl$DN)  

#Error in FUN(X[[i]], ...) : not a SpatialPolygons object
Dorothy
  • 523
  • 1
  • 5
  • 17

1 Answers1

0

I do not know what causes the error. An alternative path you could try is

library(raster)
x <- bind(poly)
y <- aggregate(x, "DN")

With example data:

set.seed(0)
r <- raster(ncol=5, nrow=5, xmn=0, xmx=1, ymn=0, ymx=1)
values(r) = sample(5, ncell(r), replace=TRUE)
rr <- list()
rr[[1]] <- crop(r, extent(0,0.5,0,0.5))
rr[[2]] <- crop(r, extent(0.5,1,0.5,1))
rr[[3]] <- crop(r, extent(0,0.5,0.5,1))
rr[[4]] <- crop(r, extent(0.5,1,0,0.5))
x <- list(r1, r2, r3, r4)  
y <- lapply(x, rasterToPolygons)


b <- bind(y) 
a <- aggregate(b, 'layer')

plot(r)
plot(a, add=TRUE)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • 1
    Thanks so much for your reply. I am now getting the following different error, though, when I apply your method to my data: 'Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘bind’ for signature ‘"SpatialPolygonsDataFrame", "missing". Maybe gdal_polygonizeR (which I need to use instead of rasterToPolygon for decreasing total runtime) creates a problem? – Dorothy Oct 19 '18 at 04:35
  • I suppose that at least one list element does not have a SpatialPDF object; perhaps because all cells were NA?. That would also explains the error you are getting with your code. Run `lapply(poly1, class)` or `lapply(poly1, is.null)` to find the list elements that you need to remove. – Robert Hijmans Oct 19 '18 at 04:56
  • 1
    Thanks for the suggestion, but using your suggested method reveals that all elements are 'SpatialPDF' and 'FALSE', so this isn't the problem. Any other suggestions? – Dorothy Oct 20 '18 at 21:44