[R-sig-Geo] passing levels to predict::raster
Michael Koehler
michael.koehler at nw-fva.de
Thu Aug 27 14:54:47 CEST 2015
|Dear List, I want to predict a model a rasterstack that includes
categorical data. The outcome is all NA. However, converting the same
rasterstack/brick to a dataframe and pedict the model gives proper
results. What am I doing wrong with passing the levels to
predict::raster? ||Here is an example:
library(raster)library(rasterVis)library(randomForest)# make a
rasterset.seed(0)r
<-raster(nrow=10,ncol=10)r[]<-runif(ncell(r))*10is.factor(r)r
<-round(r)# make faktorf <-as.factor(r)is.factor(f)# get some none-sense
levelsx <-levels(f)[[1]]x$code <-paste("A",letters[10:20])x$code2
<-paste("B",letters[10:20])x$code3 <-letters[10:20]levels(f)<-x
f<-deratify(f)# make a bricklevels(f)set.seed(2)# get some none-sense
dataframexx<-data.frame(code=sample(rep(paste("A",letters[10:20]),10)),code2=sample(rep(paste("B",letters[10:20]),10)),code3=rep(letters[10:20],10),y=as.factor(sample(rep(paste(rep(1:5)),22))))#
fit and predict a random forest with
itranfor<-randomForest(y~.,data=xx,ntree=100)predict(ranfor)# try to
predict with a
rasternames(f)<-c("code","code2","code3")a<-predict(object=f,ranfor,na.omit=T,factors=list(code=levels(xx$code),code2=levels(xx$code2),code3=levels(xx$code3)))plot(a)#
gives an empty raster# convert the raster to a dataframe and predict
againx<-as.data.frame(f)names(x)<-c("code","code2","code3")aa<-predict(ranfor,x)plot(aa)#
works just fine! |
|#R version 3.1.2(2014-10-31)Platform:x86_64-w64-mingw32/x64 (64-bit) |I was asking that also here:
http://stackoverflow.com/questions/31477064/passing-levels-to-predict-randomforest-with-a-raster
But I did not get a response.
--
Michael Kohler
[[alternative HTML version deleted]]
More information about the R-sig-Geo
mailing list