Skip to content

Multiply 2 raster without considering cells with NA

3 messages · sadaoui, Antonio Rodriges, Robert J. Hijmans

#
Hello, 

I try to multiply 2 raster (temperature and precipitation) with "overay"
function, but the problem at the same time it multiplies the NA values, then
it gives a false result.

I tried with this code ;

library(raster) ;
T = getData('worldclim', var='tmean', res=0.5, lon=5, lat=45)/10
MeanT=mean(T)
MeanT
# values      : -11.60833, 23.35833  (min, max)

P= getData('worldclim', var='prec', res=0.5, lon=5, lat=45)
cumulP=sum(P) #values      : 10, 2883  (min, max)

r <- overlay(MeanT, cumulP, fun=function(x,y){return(y/(x+10))})
r # values      : -108000, 318000  (min, max)

Normally I find the results : ~[0-120]

I searched this page :
http://www.inside-r.org/packages/cran/raster/docs/overlay
but is not mentioned.

it is mentioned in the  the "calc" function  but it is applicable only for a
single raster : http://www.inside-r.org/packages/cran/raster/docs/calc

Thank you in advance for helping me make a calculation between two raster
without counting NA values.

Best regards



--
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Multiply-2-raster-without-considering-cells-with-NA-tp7588224.html
Sent from the R-sig-geo mailing list archive at Nabble.com.
3 days later
#
Try smth like this (I did not run that and not sure in syntax)
r <- overlay(MeanT, cumulP, fun=function(x,y){if (isNA(x) || isNA(y))
return NA else return(y/(x+10))})
Kind regards,
Antonio Rodriges


2015-05-10 1:35 GMT+03:00 sadaoui <sadaouimahrez at outlook.com>:
#
These would seem to be plausible, and correct, values. I do not think
there is anything wrong NA values. The extreme values are because you
divide by a fraction. How would you expect the results to be
non-negative if you divide by negative values?

Antonio's answer is incorrect, as division with an NA value already
returns an NA value, there is no need to add a conditional statement
to deal with that.

You could use calc by first using stack, but overlay is probably clearer here.

Or use an algebraic formulation:

r <- cumulP / (MeanT+10)

Robert

On Wed, May 13, 2015 at 12:18 PM, Antonio Rodriges
<antonio.rrz at gmail.com> wrote: