rcroprasterrastervisterra

R Crop no-data of a raster


I would like to crop the no-data part of some rasters (example of the image in 1 where no-data is in black) without defining the extent manually.

Any idea?

image with no-data


Solution

  • You can use trim to remove exterior rows and columns that only have NA values:

    library(raster)
    r <- raster(ncols=18,nrows=18)
    r[39:49] <- 1
    r[205] <- 6
    s <- trim(r) 
    

    To change other values to or from NA you can use reclassify. For example, to change NA to 0:

    x <- reclassify(r, cbind(NA, 0))