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

1 Answer 1


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:

  • This is a regressive RF model, not classification so N is infinite?
    – BHope
    Apr 1 at 21:21
  • In this case you can't use the probability, only the prediction. Try to use only: names(raster_stack)<-c("x1","x2", "x3", "x4", "x5", "...") r_pred <- raster::predict(model=rf_model, object=raster_stack)
    – sermomon
    Apr 1 at 21:39
  • This worked perfectly but my predicted values are log-transformed and I don't know how to back-transform them.
    – BHope
    Apr 1 at 22:40
  • 1
    Well, you could simply back-transform the resulting raster eg., back.transform <- function(y) exp(y + 0.5 * stats::var(y, na.rm=TRUE)) then raster::calc(x, back.transform) Apr 26 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.