Search code examples
rraster

unwanted subgeometries when converting raster to polygons


I am converting many rasters to polygon. But in quite a few cases, I am seeing unexpected subgeometries, and I can't seem to get rid of them.

This is with R v3.3.3 and raster package v2.5-8.

Here is an example that should reproduce the problem I am having.

You can download the raster that I use here.

# first, read in raster and coarsen to something more manageable

library(raster)
library(rgeos)
env <- raster('adefi.tif')
env2 <-aggregate(env, 8)

# Reclassify such that cells are either 1 or NA
env2[!is.na(env2)] <- 1

# this is what the raster now looks like:
plot(env2)

enter image description here

# Now I convert to polygon, choosing to dissolve
p <- rasterToPolygons(env2, dissolve=T)

plot(p)

enter image description here

# I find that I can't get rid of these subgeometries
p <- gUnaryUnion(p) # identical result
gIsValid(p) # returns TRUE

I'm not sure where the problem is... Is it in how the raster package converts to cell polygons? Or is it how the rgeos package dissolves those cell polygons together? Is there a work-around?


Solution

  • It looks like a projection issue. This works for me:

    library(raster)
    library(rgeos)
    
    env <- raster(file.path(fp, "adefi.tif"))
    env2 <- aggregate(env, 8)
    env2[is.na(env2) == F] <- 1
    # Project Raster
    proj_env2 <- projectRaster(env2, crs = CRS("+init=epsg:3577"))
    p <- rasterToPolygons(proj_env2, dissolve = T)
    plot(p)
    

    Not sure why the need for reprojection since epsg:3577 looks to be the same as the original projection, but I usually confirm projection using proj4string() or spTransform() to make sure everything will line up.