Conditional ifelse in R for raster not working

#I am trying to calculate net annual radiation using empirical formula
#Rn=10.18+1.13Tm if Tm>=0 ;
#Rn=10.18+0.80
Tm if Tm< 0
#Tm is mean annual temperature raster.
>myFun<-function(x) {ifelse (x <0,10.18+0.80*x,10.18+1.13*x)}
>Rn<-calc(Tm, function(x){myFun(x)})

after running this i am getting the raster calculated as only by if(x <0,10.18+0.80x) nothing like ifelse(x<0,10.18+0.80x,10.18+1.13*x )
It seems else condition is not considered by the code.

Please help

Hi @Nagesh_jpf_iist,
Welcome to the RStudio Community Forum.

Your calc() statement was wrong. Try this reproducible example:

# Create some dummy data - a single raster layer.
library(raster)
#> Loading required package: sp
r <- raster(ncols=5, nrows=6)
values(r) <- -14:15
r
#> class      : RasterLayer 
#> dimensions : 6, 5, 30  (nrow, ncol, ncell)
#> resolution : 72, 30  (x, y)
#> extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> crs        : +proj=longlat +datum=WGS84 +no_defs 
#> source     : memory
#> names      : layer 
#> values     : -14, 15  (min, max)
as.matrix(r)
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]  -14  -13  -12  -11  -10
#> [2,]   -9   -8   -7   -6   -5
#> [3,]   -4   -3   -2   -1    0
#> [4,]    1    2    3    4    5
#> [5,]    6    7    8    9   10
#> [6,]   11   12   13   14   15

# Define custom function and run 
myFun <- function(x) {ifelse(x < 0, 10.18+0.80*x, 10.18+1.13*x)}
Rn <- calc(r, myFun)
Rn
#> class      : RasterLayer 
#> dimensions : 6, 5, 30  (nrow, ncol, ncell)
#> resolution : 72, 30  (x, y)
#> extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> crs        : +proj=longlat +datum=WGS84 +no_defs 
#> source     : memory
#> names      : layer 
#> values     : -1.02, 27.13  (min, max)
as.matrix(Rn)
#>       [,1]  [,2]  [,3]  [,4]  [,5]
#> [1,] -1.02 -0.22  0.58  1.38  2.18
#> [2,]  2.98  3.78  4.58  5.38  6.18
#> [3,]  6.98  7.78  8.58  9.38 10.18
#> [4,] 11.31 12.44 13.57 14.70 15.83
#> [5,] 16.96 18.09 19.22 20.35 21.48
#> [6,] 22.61 23.74 24.87 26.00 27.13

Created on 2021-03-03 by the reprex package (v1.0.0)

HTH

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.