Skip to content
Prev 24351 / 29559 Next

problem with predict() in package raster and factor variables

Dear Frede and list,

My sincere apologies for not providing sufficient information or reproducible example. As a matter of fact, you are right and when I looked further into the data I used to estimate the random forest model I solved the problem myself! In case it's of interest, the problem was that the variable had to be converted to a factor *before* fitting the model, so that the result of str(v) should not be what I showed in my original mail, but instead it should be:

'data.frame':	1257 obs. of  15 variables:
 $ RefNo      : int  16 16 16 16 17 17 17 17 18 18 ...
 $ PointID    : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Count      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ PA         : int  0 0 0 0 0 0 0 0 0 0 ...
 $ split      : chr  "T" "T" "T" "T" ...
 $ bathy20_1  : num  256 260 252 266 281 ...
 $ TerClass   : Factor w/ 6 levels "1","2","3","4",..: 2 2 1 1 1 2 1 1 3 3 ...

etc

Note that before, $TerClass was num, and now it's Factor w/ 6 levels

And f should look like this:

$TerClass
[1] "1" "2" "3" "4" "5" "6"

Then the predict() function works without any problems!

Furthermore, there is an example in the help file that exactly represents my case, namely this bit:

# create a RasterStack or RasterBrick with with a set of predictor layers
logo <- brick(system.file("external/rlogo.grd", package="raster"))
# known presence and absence points
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 
              66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 
              22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9,
              99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21,
              37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2)
# extract values for points
xy <- rbind(cbind(1, p), cbind(0, a))
v1 <- data.frame(cbind(pa=xy[,1], extract(logo, xy[,2:3])))
# cforest (other Random Forest implementation) example with factors argument
v1$red <- as.factor(round(v1$red/100))
logo$red <- round(logo[[1]]/100)
library(party)
m <- cforest(pa~., control=cforest_unbiased(mtry=3), data=v1)
f1 <- list(levels(v1$red))
names(f1) <- 'red'
pc <- predict(logo, m, OOB=TRUE, factors=f1)

Thank you all very much, and my apologies for wasting anyone's time.

Genoveva