4
votes

I'm sure if this is possible in R, and if someone knows of a way to do this with some other program please let me know

Currently I have a raster, and I need to turn a group of pixels into an NA group if there isn't a large enough cluster. My current thought process was to convert the raster to a polygon, and then calculate the polygons area and remove the polygons if they weren't large enough. The only problem with this is that rasterToPolygon creates a single layer of polygons, and I have no way of individually indexing each one. Any ideas? Here is an example:

library(raster)
area <- raster(matrix(c(1:4,1),5,5))
shape <- rasterToPolygons(area,fun=function(x){x == 1},dissolve=TRUE)

Example

1
are your groups in your raster always structured in lines? or can the groups be randomely diestributed over the raster?maRtin

1 Answers

2
votes

After dissolving, you can disaggregate the multipart polygon into single part polygons again. The disaggregate method for SpatialPolygons* is in the sp package (which should already be loaded if you have raster loaded).

library(sp)
shape2 <- disaggregate(shape)

shape2
## class       : SpatialPolygonsDataFrame 
## features    : 2 
## extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
## coord. ref. : NA 
## variables   : 1
## names       : abc 
## min values  :   1 
## max values  :   1 

Polygons will have an attribute that indicates the value their original raster value. You could then, for example, add an attribute giving each polygon a unique ID.

shape2$id <- factor(seq_len(length(shape2)))
spplot(shape2, 'id')

enter image description here