[R-sig-Geo] Predict GAM model with categorical predictors

Thiago Cesar Lima Silveira thiagoclsilveira at yahoo.com.br
Tue Nov 11 18:39:00 CET 2014


Hi,

Sorry, I've posted the 
code with some mistakes.
Consider the code below.

I've one response, and two predictors, 
v1 (numeric) and v2 (factor).
 So, I have just one predictor
 which is possible to have a raster, the other is a categorical
variable.

How to predict to rasters considering categorical variables?

As described in the package raster,
 "const" is used as a constant for which there is no Raster 
object for model predictions.

In my case categorical variable. 

I'm using this argument and doesn't work. Any Idea?

######

library(mgcv)
library(raster)
library(rgdal)

#raster example
v1rst<-raster()
values(v1rst) <- 1:ncell(v1rst)
names(v1rst)<-'v1'
plot(v1rst)

# Example of response variable and predictors
y<-c(1,33,500,700, 334,320, 703,
+ 303,3030,3002,200,0,100,100,169)
v1<-c(12,33,544,600, 34,30, 03,3390,3030,
 + 302,20,108,170,101,2009)
v2<-c('t','t','t','t','t','t','t','t','c','c','c','c','c','c','c' )
df<-data.frame(y, v1, v2)

#GAM model with factor
gam1<-gam(y~s(v1)+factor(v2), data=df)
summary(gam1)

#GAM model without factor
gam2<-gam(y~s(v1), data=df)
summary(gam2)

#GLM with factor
glm1<-glm(y~v1 + factor(v2), data=df)
summary(glm1)

#GLM no factor
glm2<-glm(y~v1, data=df)
summary(glm2)


# data.frame with a constant value 
#(of class ’factor’) to pass that on to the predict function.
v2<-factor( 't',levels=levels(df$v2)) 
add2<-data.frame(v2)
str(add2)              

#Prediction with factor
p<-predict(v1rst,gam1, const=add2, type='response')

#This is the error
 'Error in `[.data.frame`(blockvals, , f[j]) : undefined columns selected
              
#Prediction without factor
p<-predict(v1rst,gam2, type="response")
plot(p)

#Prediction glm

glm1p<-predict(v1rst, glm1, type='response', const=add2)

glm2p<-predict(v1rst, glm2, type='response')
plot(glm2p)



More information about the R-sig-Geo mailing list