Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace Raster Values Less than 0 to NA in R code

Tags:

r

na

raster

I am working with Landsat imagery to calculate net radiation. There are very low negative values (ex: -0.000003) that are in my converted reflectance raster layers. I want to make sure that my reflectances are 0 - 1 in order to reduce error in my future calculations.

How can I replace raster values less than 0 to "NA" in R. Similar to a raster calc function. I'm unsure how to provide an example, but I'm certain one of you could help me, yes?

Here is my equation for the reflectivity derived from Bastiaanssen et al. (1998)

Assuming, the pb1 indicates the reflectance for band 1 of Landsat, pi = 3.14..., lb1 = radiance for band 1, ESUN = exoatmospheric value for band 1, dr = the relative earth sun distance for the day of year.

#Calculate reflectivity per band. QC: Always 0 to 1
pb1 = (pi * lb1)/(ESUN1 * cos(solzen) * dr)

After this raster is created, all I want to do is set the pb1 values that are less than 0 to NA.

Help?

like image 797
MaeAntoinette Avatar asked Apr 30 '16 22:04

MaeAntoinette


People also ask

How do I remove zero values from raster R?

Just use the missing value NA to replace the 0. Sometimes, a special number indicates missing value in a raster (such as -999 or any obvious value that will be outside the range of the normal dataset you are working with).

What is a raster object in R?

An object of class "raster" is a matrix of colour values as given by rgb representing a bitmap image. It is not expected that the user will need to call these functions directly; functions to render bitmap images in graphics packages will make use of the as.


2 Answers

With the raster package, the memory-safe way to do this is to use reclassify or clamp

library(raster)
r <- raster(ncol=10, nrow=10)
values(r) <- rnorm(100)
x <- clamp(r, useValues=FALSE)
y <- reclassify(r, cbind(-Inf, 0, NA), right=FALSE)

Note the right=FALSE to not set cells that are zero to NA.

These methods are memory-safe and you can also provide a filename argument so that you do not need to call writeRaster afterwards.

like image 190
Robert Hijmans Avatar answered Nov 15 '22 22:11

Robert Hijmans


library(raster)

values(pb1)[values(pb1) < 0] = NA

Or, as suggested by @jbaums:

pb1[pb1 < 0] <- NA

If you want to keep the original raster object, remember to assign the original raster to a new object name before running the code above.

like image 38
eipi10 Avatar answered Nov 15 '22 21:11

eipi10