Skip to content

new function predict, package raster

10 messages · isabelle boulangeat, Robert J. Hijmans

#
Isabelle,

If you use a factor that is represented by numbers on a grid you can
just fit the model (with the factor variable as factor), and the
predict function will then make a factor from the predictor layers
(i.e. there is nothing else you need to do). Where this can go wrong
is if you have factor levels on your raster that were not in the data
used to fit the model. You can get something like:
Error in model.frame.default(Terms, newdata, na.action = na.action,
xlev = object$xlevels) :
  factor 'x' has new level(s):  2, 3, 4, 5,
Which means that you first need to remove those levels (set to NA)
from your predictor raster. (I will try to automate that problem away,
in raster::predict, eventually)

The argument "const" is for factor type variables for which you do not
have spatial data. Hence they could be considered 'constant' in some
contexts. For example, with fish observation data you might have a
model that predicts abundance from a number of variables including the
method used to catch the fish. Say a factor variable "method" with
levels "A" or "B". You can then do something like
method = factor("A")
predict(raster, model, const=method)

Robert

On Thu, Dec 2, 2010 at 9:02 AM, isabelle boulangeat
<isabelle.boulangeat at gmail.com> wrote:
#
Dear Isabelle,

Thanks for the detailed report. So it is a bug after all. This is
probably fixed in raster 1.7-8 (on CRAN for win and lin now).
At least the below works for me (model with 2 variables, one is a factor).

Robert

library(raster)
# create a RasterStack (a set of predictor rasters)
logo <- stack(system.file("external/rlogo.grd", package="raster"))
presence <- 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)
background <- cbind(runif(250)*(xmax(logo)-xmin(logo))+xmin(logo),
runif(250)*(ymax(logo)-ymin(logo))+ymin(logo))

xy <- rbind(cbind(1, presence), cbind(0, background))
v <- cbind(xy[,1], extract(logo, xy[,2:3]))
colnames(v)[1] <- 'presback'
v=data.frame(v[,1:3])
v[,3] <- as.factor(v[,3])

model <- glm(formula=presback~., data=v)
r <- predict(logo, model, progress='text')




On Fri, Dec 3, 2010 at 3:26 AM, isabelle boulangeat
<isabelle.boulangeat at gmail.com> wrote:
2 days later
2 days later
#
Isabelle, I think I fixed this in raster 1.7-11. Robert

On Wed, Dec 8, 2010 at 8:55 AM, isabelle boulangeat
<isabelle.boulangeat at gmail.com> wrote:
4 days later
9 days later
#
Isabelle, I think you nailed it. The function now sets the levels and
things seem to work well (version 1-7.19). Thanks! Robert

On Thu, Dec 23, 2010 at 3:54 AM, isabelle boulangeat
<isabelle.boulangeat at gmail.com> wrote: