rrandom-forestpredictterra

Terra predict function failing to predict my random forest model


I have a csv. with my data and I put it through a RF to predict sediment type based off of bathymetry data from 24 sample points (and get sediment distribution as an image output), the RF is working as it should but when I try to use the terra predict function with a predictor raster it won't predict.

env  = read.csv("./data/green_environmental.csv")
head(env)

names(env) = c("Station", "Sediment", "Details", "Feature", "latitude", "longitude", "u5", "u4","Bathymetry", "bathy_pei", "Backscatter", "bathy_200khz", "bathy_300khz", "temp_c", "conductivity_mS_cm", "salinity_PSU", "density_kg_m3", "cluster_untransformed","cluster_1", "cluster_2")

bathy_pei = terra::rast("./data/bathymetry_full.tif")

env$Sediment = as.factor(env$Sediment)

rf_a = randomForest(Sediment ~ bathy_pei, env)
rf_a

# this one gets an error
rf_pred = terra::predict(bathy_pei, model=rf_a, na.rm = FALSE)

This is the error I get:

Error in model.frame.default(Terms, newdata, na.action = na.omit) : object is not a matrix

In addition:

Warning message: 'newdata' had 19328 rows but variables found have 11136 rows

I tried using na.rm and na.action. I have checked my raster layer (floating point geotiff) it seems fine, changing the raster name hasn't done anything and I tried converting my data to a matrix but then the RF wouldn't run.


Solution

  • Rename the SpatRaster so it has the same name as the predictor variable in your model.

    names(bathy_pei) <- 'bathy_pei'
    rf_pred = terra::predict(bathy_pei, model=rf_a, na.rm = FALSE)