TransWikia.com

Remove NA from Raster Layer

Geographic Information Systems Asked by obrob on May 7, 2021

I have a RasterLayer and a SpatialPolygonDataFrame.

I used the mask function to create a new RasterLayer.

The output is correct but it does include lot’s of NA values.

Now I want to get rid of the NA values.

Is there an efficient way to solve this problem?

3 Answers

A raster is an array and is always square (rectangular), regardless of where the data occurs. Unless you have a perfectly square extent of data you will have NA values, this is part of the point of storing data in an array format. Now, one thing that does occur is that you have an extent much larger than necessary resulting in spurious NA values. In this case the raster can be subset to a smaller extent using the crop function.

When masking to a polygon, A good procedure using the raster library, is to use crop in conjunction with mask. The ensures that these spurious NA values, representing an unnecessarily large extent of empty space, are removed.

Now, there are cases where the nodata is actually a background. Here is where you can use indexing to replace NA values with real values representing a background, eg., x[is.na(x)] <- 0 This is common when representing a binomial process where 1 is a element of interest and the background represents an element to compare against (eg., forest/nonforest). Sometimes, in processing, the the background becomes nodata. Here is where setting NA values to a real value becomes relevant. However, one must keep in mind the edge effect. If your area of interest is irregular in shape, the areas outside are still real nodata values. This is where masking comes in.

Correct answer by Jeffrey Evans on May 7, 2021

If you mask any raster you probably will obtain NA values, even more using SpatialPolygonDataFrame as mask.

You have two posible options, if SpatialPolygonDataFrame is a rectangle, use crop() before mask to reduce raster's extend. Second option, change NA values to other value, such 0 or -9999:

r <- raster(ncol=10, nrow=10)
m <- raster(ncol=10, nrow=10)
r[] <- runif(ncell(r)) * 10
m[] <- runif(ncell(r))
m[m < 0.5] <- NA
mr <- mask(r, m)

mr[is.na(mr)] <- 0

Answered by aldo_tapia on May 7, 2021

If like me you have inconsistency in the NA values in a rasterstack / brick, do the following:

namask = sum('rasterbrick)

new.rasterbrick = raster::mask('rasterbrick', namask)

Answered by David on May 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP