I used this to predict values on a raster stack but the values then need to be back-transformed as they are log values:
r_pred <- raster::predict(model=rf_model, object=raster_stack)
I tried (but it did not work):
values(r_pred) <- exp(r_pred)
Reclassify()
looks promising but I am not sure where to start?
The short answer is: you can likely just use:
r_back_transformed = exp(r_pred)
The long answer is that from the values
docs:
In most cases it is better to use getValues rather than values. values is typically used in functions after a read* function has been used and it will return all the values that happen to be in memory at that point, or fail if there are no values in memory. In contrast getValues will read values from disk if necessary.
So you could use a combination of raster::getValues()
and raster::setValues()
. As in:
raster::setValues(r_pred) <- exp(raster::getValues(r_pred))
However, in most cases you can directly use the calc
or stackApply
functions. For example:
r_back_transformed = raster::calc(r_pred, exp)
applies the exp
functions to all layers of r_pred
.
However, for a number of functions, raster algebra is natively implemented; from raster
documentation chapter four: raster algebra):
Many generic functions that allow for simple and elegant raster algebra have been implemented for Raster* objects, including the normal algebraic operators such as +, -, *, /, logical operators such as >, >=, <, ==, !} and functions such as abs, round, ceiling, floor, trunc, sqrt, log, log10, exp, cos, sin, max, min, range, prod, sum, any, all. In these functions you can mix raster objects with numbers, as long as the first argument is a raster object.
And you can use r_back_transformed = exp(r_pred)
.
Finally, terra::values()
corresponds to raster::getValues()
/raster::setValues()
which may explain your initial intuition, and terra
, the replacement of raster
, natively supports some raster algebra. For non-natively supported functions, terra::app
maps to raster::calc
.