I need to convert all rasters in a RasterStack to polygons and give the polygons names according to its respective raster.


## r is a single raster
rpolygon <- rasterToPolygons(r, dissolve = TRUE)

## rstack is a raster stack
lapply(rstack, rasterToPolygons)

But this lapply function returned the following error.

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘nlayers’ for signature ‘"numeric"’

1 Answer 1


lapply(r,..) fails because even though a stack has some semantics of a list (like defining r[[1]] to r[[N]]) that's not sufficient for lapply to work with a raster stack.

Convert your stack to a list of single-band rasters with as.list, then lapply as usual:

My stack:

> s
class       : RasterStack 
dimensions  : 4, 4, 16, 3  (nrow, ncol, ncell, nlayers)
resolution  : 0.25, 0.25  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
names       : layer.1, layer.2, layer.3 
min values  :       1,       1,       1 
max values  :       2,       2,       2 

lapply as a list:

> polylist = lapply(as.list(s), rasterToPolygons)

Output is a list of polygon layers:

> str(polylist, max=2)
List of 3
 $ :Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
 $ :Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
 $ :Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots

No other packages need installing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.