JerryN
JerryN

Reputation: 2506

R raster construct new raster from two existing rasters

I need to construct a new raster (called ch based on two rasters (called tmin and tmax) based on the following logic. Each element of the new raster follows this logic. tmin, tmax and ch are all raster bricks with identical dimensions but I thought I'd experiment with just single layers first.

if (tmin > 7) ch <- 0
if (tmax < 7) ch <- 24
else
ch <- (7 - tmin)/(tmax - tmin)

I tried to follow the logic of this answer with the following code. testout consists of zeros or 24s as expected. I can't figure out how to get the last part of the logic into this process.

library(raster)
r1 <- raster()
r2 <- raster()
set.seed(10)
values(r1) <- runif(ncell(r1), min = 0, max = 10)
values(r2) <- runif(ncell(r2), min = 0, max = 10)

myFun <- function(r1, r2) {
  0*(r1 > 7)+
  24*(r2 < 7)  
}

testout <- myFun(r1, r2)

Upvotes: 0

Views: 67

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

Example data

library(raster)
r1 <- r2 <- raster(ncol=10, nrow=10)
set.seed(10)
values(r1) <- runif(ncell(r1), min = 0, max = 10)
values(r2) <- runif(ncell(r2), min = 0, max = 10)

Vectorized function

myFun <- function(tmin, tmax) {
    ch <- (7 - tmin)/(tmax - tmin)
    ch[tmin > 7] <- 0
    ch[tmax < 7 & tmin <= 7] <- 24
    ch
}

ch1 <- overlay(r1, r2, fun=myFun)

Undocumented alternative

ifel <- raster:::.ifel
ch2 <- ifel(r1 > 7, 0, ifel(r2 < 7, 24, (7 - r1)/(r2 - r1)))

Upvotes: 1

Related Questions