Hi all,

I want to use raster package predict function for models that have been 
setted up with factorial variables (under character format). It seems to 
be impossible. It works if factorial variables are coded with integer 
values but failed if coded with characters. Here an example with the 2 
case described above:

#############################################################
rm(list=ls(all.names=T))
library(raster)

### 1st case : Fail if factorial variables are not integer 
###################
data <- data.frame(a=rnorm(100), b=factor(rep(c("x","y"),length.out=100)))

# create raster stack equivalent for our data.frame
a_ras <- b_ras <- raster(nrows=10, ncols=10)
a_ras[] <- data[,"a"]
b_ras[] <- data[,"b"]
data_ras <- stack(a_ras,b_ras)
names(data_ras) <- c("a","b")
is.factor(data_ras)

# create a response variable
resp <- sample(c(0,1), 100, replace=T)

# build a model
mod <- glm(resp~., data=data, family='binomial')

# try to make predictions
pred_df <- predict(mod,data)
pred_ras <- predict(data_ras,mod)

# only NA's in raster of prediction
pred_ras

### 2nd case : OK if factorial variables are integer 
########################
data <- data.frame(a=rnorm(100), b=factor(rep(c(1,2),length.out=100)))

# create raster stack equivalent for our data.frame
a_ras <- b_ras <- raster(nrows=10, ncols=10)
a_ras[] <- data[,"a"]
b_ras[] <- data[,"b"]
data_ras <- stack(a_ras,b_ras)
names(data_ras) <- c("a","b")
is.factor(data_ras)

# create a response variable
resp <- sample(c(0,1), 100, replace=T)

# build a model
mod <- glm(resp~., data=data, family='binomial')

# try to make predictions
pred_df <- predict(mod,data)
pred_ras <- predict(data_ras,mod)

## OK
pred_ras
#############################################################

Does someone have a trick to deal with this issue? (I need to keep 
factorial variables has character to prevent from other issues)

Any help would be appreciated.

Best,
Damien.






	[[alternative HTML version deleted]]

