Problems putting transformed predictions from Random Forest back into raster format in R

random forestraster

The problem comes when I try to put the values back into raster format to plot. Here is the code:

Rstack <- Rstack[[name]]              # match names in raster stack to same order as model 
data_vals <- values(Rstack)           # convert raster to values
map_rftree <- predict(rf_tree1000, newdata = data_vals, missing = NA)    # make predictions
map_rftree_trans <- exp(map_rftree)   # back transform values
r <- Rstack[[3]]                      # use any raster from data set as template for predictions 
values(r) <- map_rftree_trans         # assign the predicted values to it

I get this error.

Error in setValues(x, value) : 
  length(values) is not equal to ncell(x), or to 1

I check and see lengths are not equal but I am not sure how to fix this.

> length(r)
[1] 90632698
> length(map_rftree_trans)
[1] 22023903

Best Answer

The raster package allows to predict using a RandomForest model directrly over the RasterStack containing the predictors.

Suppose the rf_model variable contains your fitted model (classification model) and raster_stack is the RasterStack containing your predictors.

First, define the names of the RasterStack's layers. Make sure they are the same names as when you trained your model.

names(raster_stack)<-c("x1","x2", "x3", "x4", "x5", "...")

Then you can predict the value or the probability using as follows:

N = 3
r_pred <- raster::predict(model=rf_model, object=raster_stack)
r_prob <- raster::predict(model=rf_model, object=raster_stack, type="prob", index=1:N)

where N is the number of classes to classify.

Finally plot the results:

plot(r_pred)
plot(r_prob)