UseR10085
UseR10085

Reputation: 8166

ifelse returning attempt to replicate an object of type 'S4' error in R

I am trying to set the values of E raster as 0.987 where b is over 0.5, otherwise use whatever was in E. For that, I am using the following code

a <- raster::raster(ncol=100, nrow=100)
set.seed(2)
raster::values(a) = runif(10000, min=0.1, max=0.4)
b <- raster::raster(ncol=100, nrow=100)
set.seed(2)
raster::values(b) = runif(10000, min=0.02, max=0.8)

c <- ((b - 0.2)/(0.5 - 0.2))^2
dE <- (1 - 0.9747)*(1 - c)*0.55*0.9896
E <- raster::raster(b)
E[] = ifelse(b[]>0.5, 0.989+dE, E[])

which returns me following error

Error in rep(yes, length.out = len) : attempt to replicate an object of type 'S4'

How can I fix this error?

Upvotes: 1

Views: 786

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

You can use terra::ifel for this

library(terra)
set.seed(2)
a <- rast(ncols=10, nrows=10)
values(a) = runif(100, min=0.1, max=0.4)
b <- setValues(a, runif(100, min=0.02, max=0.8))    
c <- ((b - 0.2)/(0.5 - 0.2))^2    
dE <- (1 - 0.9747)*(1 - c) * 0.55 * 0.9896 + 0.989

E <- ifel(b>0.5, dE, b)

This is equivalent to

x <- mask(dE, b>0.5, maskvalues=0)
e <- cover(x, b)

See

plot(e, E); abline(0,1)

Upvotes: 2

Related Questions