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) andraster_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.
Then you can predict the value or the probability using as follows:
where N is the number of classes to classify.
Finally plot the results: