5

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?

10

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.

4

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
1

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)

D

  • 1
    This approach can have somewhat variable and unexpected outcomes, what exactly is the expected output with this example and how does it address the OP's problem? When answering a question please provide ample information as to how your recommendation addresses the problem and if providing code, a worked, reproducible example. – Jeffrey Evans Mar 12 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.