## These commands write new files to your working directory
# Use the iris data
data(iris)
# Section 1: Imagine that the iris are planted in a planting bed.
# The following set of commands create Asciigrid map
# files for four attributes to illustrate the planting layout.
# Change species from a character factor to numeric (the sp classes
# can not handle character data).
sLen <- matrix(iris[,1],10,15)
sWid <- matrix(iris[,2],10,15)
pLen <- matrix(iris[,3],10,15)
pWid <- matrix(iris[,4],10,15)
spcd <- matrix(as.numeric(iris[,5]),10,15)
# Make maps of each variable.
header = c("NCOLS 15","NROWS 10","XLLCORNER 1","YLLCORNER 1",
"CELLSIZE 1","NODATA_VALUE -9999")
cat(file="slen.txt",header,sep="")
cat(file="swid.txt",header,sep="")
cat(file="plen.txt",header,sep="")
cat(file="pwid.txt",header,sep="")
cat(file="spcd.txt",header,sep="")
write.table(sLen,file="slen.txt",append=TRUE,col.names=FALSE,
row.names=FALSE)
write.table(sWid,file="swid.txt",append=TRUE,col.names=FALSE,
row.names=FALSE)
write.table(pLen,file="plen.txt",append=TRUE,col.names=FALSE,
row.names=FALSE)
write.table(pWid,file="pwid.txt",append=TRUE,col.names=FALSE,
row.names=FALSE)
write.table(spcd,file="spcd.txt",append=TRUE,col.names=FALSE,
row.names=FALSE)
# Section 2: Create functions to predict species
# set the random number seed so that example results are consistant
# normally, leave out this command
set.seed(12345)
# sample the data
refs <- sample(rownames(iris),50)
y <- data.frame(Species=iris[refs,5],row.names=rownames(iris[refs,]))
# build a yai imputation for the reference data.
rfNN <- yai(x=iris[refs,1:4],y=y,method="randomForest")
# make lists of input and output map files.
xfiles <- list(Sepal.Length="slen.txt",Sepal.Width="swid.txt",
Petal.Length="plen.txt",Petal.Width="pwid.txt")
outfiles1 <- list(distance="dist.txt",Species="spOutrfNN.txt")
# map the imputation-based predictions for the input maps
AsciiGridImpute(rfNN,xfiles,outfiles1,ancillaryData=iris)
# build a randomForest predictor
rf <- randomForest(x=iris[refs,1:4],y=iris[refs,5])
# map the predictions for the input maps
outfiles2 <- list(predict="spOutrf.txt")
AsciiGridPredict(rf,xfiles,outfiles2,xtypes=NULL,rows=NULL)
# read the species maps and plot them using the sp package classes
if (require(sp)) {
spOrig <- read.asciigrid("spcd.txt")
sprfNN <- read.asciigrid("spOutrfNN.txt")
sprf <- read.asciigrid("spOutrf.txt")
dist <- read.asciigrid("dist.txt")
par(mfcol=c(2,2))
image(spOrig)
title("Original")
image(sprfNN)
title("Using Predict")
image(sprf)
title("Using Impute")
image(dist)
title("Neighbor Distances")
}
Run the code above in your browser using DataLab