R Crop no-data of a raster R Crop no-data of a raster r r

R Crop no-data of a raster


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] <- 1r[205] <- 6s <- 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))


[ subsetting and [<- replacement methods are defined for raster objects so you can simply do r[ r[] == 1 ] <- NA to get rid of the values where 1 is your nodata value (use NAvalue(r) to find out what R considers your nodata value is supposed to be if you aren't sure).

Note you have to use r[] inside the [ subsetting command to access the values. Here is a worked example...

Example

#  Make a raster from system filelogo1 <- raster(system.file("external/rlogo.grd", package="raster"))#  Copy to see differencelogo2 <- logo1#  Set all values in logo2 that are > 230 to be NAlogo2[ logo2[] > 230 ] <- NA#  Observe differencepar( mfrow = c( 1,2 ) )plot(logo1)plot(logo2)

enter image description here


I have 2 slightly different solutions. The first requires to manually identify the extent but uses predefined functions. The second is more automatic, but a bit more handmade.

Create a reproducible raster for which the first 2 rows are NA

library(raster)# Create a reproducible exampler1 <- raster(ncol=10, nrow=10)# The first 2 rows are filled with NAs (no value)r1[] <- c(rep(NA,20),21:100)

Solution #1

Manually get the extent from the plotted figure using drawExtent()

plot(r1)r1CropExtent <- drawExtent()

Crop the raster using the extent selected from the figure

r2 <- crop(r1, r1CropExtent)

Plot for comparison

layout(matrix(1:2, nrow=1))plot(r1)plot(r2)

Solution #2

It identifies the rows and columns of the raster that only have NA values and remove the ones that are on the margin of the raster. It then calculate the extent using extent().

Transform the raster into a matrix that identifies whether the values are NA or not.

r1NaM <- is.na(as.matrix(r1))

Find the columns and rows that are not completely filled by NAs

colNotNA <- which(colSums(r1NaM) != nrow(r1))rowNotNA <- which(rowSums(r1NaM) != ncol(r1))

Find the extent of the new raster by using the first ans last columns and rows that are not completely filled by NAs. Use crop() to crop the new raster.

r3Extent <- extent(r1, rowNotNA[1], rowNotNA[length(rowNotNA)],   colNotNA[1], colNotNA[length(colNotNA)])r3 <- crop(r1, r3Extent)

Plot the rasters for comparison.

layout(matrix(1:2, nrow=1))plot(r1)plot(r3)