See if this works. The gist is to:
-read in the list of genera and orders
--loop through each order
---loop over each genus in this order
----get a list of all .asc files for this genus
----loop over these .asc files, combining them for overall richness
--write out a richness .asc file for each order
You'll obviously need to change the variables up the top, and add in your thresholding code if need be. I don't have any .asc files to test this with, so I haven't changed the last section of the code and I haven't actually tested this to see if it works.
Stewart
############################
library(SDMTools)
working.dir = ~/"mydata/";
ascii.dir = "sdms/" #define the directory of the species ascii files
genusOrder.file <- "genus-order.txt" # this should be a tab-delimited file with two columns and a heading of "Genus\tOrder"
setwd(working.dir) #define and set the working directory
order.info = read.table(genusOrder.file, header=T, sep="\t") #read in the table of order and genus
for (ord in unique(
order.info$Order)) {
cat('Doing order:', ord,'\n')#cycle through each order
#out = NULL #define the output
theseGenera =
order.info$Genus[which(
order.info$Order==ord)] #get the species in this order
for (thisGenus in theseGenera) {
cat('\tDoing genus', thisGenus, '\n')#cycle through each species in that order
theseSpecies <- list.files(ascii.dir, pattern=paste(thisGenus, "*", sep=''))
for (theseSpecies.file in theseSpecies) {
cat('\t\tDoing', theseSpecies.file, '\n')
tasc = read.asc( paste(ascii.dir, theseSpecies.file, sep='') ) #read in the species ascii
###you need to apply a threshold if it has not been applied... I am assuming that the species ascii is binary (0,1)
if (is.null(out)) { #if out is null, create the basic output asc as the first species distribution
out = tasc #copy the species distribution
} else { # if out has some data, add the next species to it
out = out + tasc #add on the species data
}
}
}
write.asc(out, paste(ord, "_richness.asc", sep='')) #write out the richness for the order