Cannot coerce class to a data.frame

data-framerrandom forestraster

I'm using R to run a random forest to predict the distribution of sediment classes in a study area. I have a .csv of the locations where sediment has been sampled, and rasters of all my predictor variables.

bbpi <- raster("broadbpi_st.tif")
east <- raster("eastness.tif")
fbpi <- raster("finebpi_st.tif")
bath <- raster("gebco_bathymetry.tif")
north <- raster("northness.tif")
curd <- extractByMask(raster("current_direction.tif"), msk= bath, spatial = TRUE)
curm <- extractByMask(raster("current_magnitude.tif"), msk=bath, spatial=TRUE)
#rug <- raster("rugosity.tif")
slope <- extractByMask(raster("slope_final.tif"), msk=bath, spatial=TRUE)
area <- extractByMask(raster("surface_planar_arearatio.tif"), msk=bath, spatial=TRUE)
umean <- extractByMask(raster("ustar_mean.tif"),msk=bath, spatial=TRUE)
umax <- extractByMask(raster("ustarmax_IDW.tif"),msk=bath, spatial=TRUE)
wmax <- extractByMask(raster("wavepower_max_IDW.tif"),msk=bath, spatial=TRUE)
wmean <- extractByMask(raster("wavepower_mean.tif"),msk=bath, spatial=TRUE)
rfstack <- stack(bbpi,fbpi,bath,east,north,curd,curm,slope,area,umean,umax,wmax,wmean)
names(rfstack) <- c("bbpi","fbpi","bath","east","north","curd","curm","slope","area","umean","umax","wmax","wmean")

points <- read.csv("bottomgrabs.csv")
set.seed(321)
rf1 <- randomForest(factor(DEPOT_GRO) ~ ., data=points, ntree=500, mtry=10, na.action=na.omit)

test1 <- raster::predict(rf1,newdata=rfstack,type="prob")

I get the following error:

Error in as.data.frame.default(newdata) :
cannot coerce class ‘structure("RasterStack", package = "raster")’ to a data.frame

How do I fix this and make my random forest run?

Best Answer

You should be able to get this to run by converting the raster stack yourself. For example, I've replicated your error with a trivial test data set:

> raster::predict(rf1, newdata=rstack)
Error in as.data.frame.default(newdata) : 
  cannot coerce class ‘structure("RasterStack", package = "raster")’ to a data.frame

and this runs:

> raster::predict(rf1, newdata=as.data.frame(rstack))
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 
 B  C  C  C  A  A  A  A  C  A  A  A  C  B  A  A 
Levels: A B C