# NOT RUN {
library(sf)
library(raster)
library(caret)
library(viridis)
library(latticeExtra)
# prepare sample data:
dat <- get(load(system.file("extdata","Cookfarm.RData",package="CAST")))
dat <- aggregate(dat[,c("VW","Easting","Northing")],by=list(as.character(dat$SOURCEID)),mean)
pts <- st_as_sf(dat,coords=c("Easting","Northing"))
pts$ID <- 1:nrow(pts)
studyArea <- stack(system.file("extdata","predictors_2012-03-25.grd",package="CAST"))[[1:8]]
trainDat <- extract(studyArea,pts,df=TRUE)
trainDat <- merge(trainDat,pts,by.x="ID",by.y="ID")
# visualize data spatially:
spplot(scale(studyArea))
plot(studyArea$DEM)
plot(pts[,1],add=TRUE,col="black")
# first calculate the AOAI based on a set of variables with equal weights:
variables <- c("DEM","Easting","Northing")
AOA <- aoa(trainDat,studyArea,variables=variables)
spplot(AOA$AOAI, col.regions=viridis(100),main="Applicability Index")
spplot(AOA$AOA,col.regions=c("grey","transparent"),main="Area of Applicability")
# or weight variables based on variable improtance from a trained model:
set.seed(100)
model <- train(trainDat[,which(names(trainDat)%in%variables)],
trainDat$VW,method="rf",importance=TRUE,tuneLength=1)
print(model) #note that this is a quite poor prediction model
prediction <- predict(studyArea,model)
plot(varImp(model,scale=FALSE))
#
AOA <- aoa(trainDat,studyArea,model=model,variables=variables)
spplot(AOA$AOAI, col.regions=viridis(100),main="Applicability Index")
#plot predictions for the AOA only:
spplot(prediction, col.regions=viridis(100),main="prediction for the AOA")+
spplot(AOA$AOA,col.regions=c("grey","transparent"))
# }
Run the code above in your browser using DataLab