I've hit a bit of a stumbling block regarding conditional statements with multiple measured variables. Briefly, I have two measured habitat gradients in vector forms, a classification scheme of habitat types based on the values of both habitat gradients, and I'd like to write a bit of code that allows me to classify all 5K of my samples as one of the habitat types using the two measurements. I can produce a bit of code that gives me a fine output if I hand it one sample at a time:
(Simplified Version)
hab.assign<-function(HabA,HabB){
if(HabA < 5 & HabB < 5){
habitat<-c("Habitat Type 1")} else
if(HabA > 5 & HabB < 5){
habitat<-c("Habitat Type 2")} else
if(HabA < 5 & HabB > 5){
habitat<-c("Habitat Type 3")} else
if(HabA < 5 & HabB < 5){
habitat<-c("Habitat Type 4")}
habitat
}
Now, if I write a piece of code to apply that function to both of my vectors over the entire 5K samples, say something like this:
all.habs<-function(HabA,HabB){
n<-length(HabA)
hab.units<-vector("character",n)
hab.assign<-function(HabA,HabB){
if(HabA < 5 & HabB < 5){
habitat<-c("Habitat Type 1")} else
if(HabA > 5 & HabB < 5){
habitat<-c("Habitat Type 2")} else
if(HabA < 5 & HabB > 5){
habitat<-c("Habitat Type 3")} else
if(HabA < 5 & HabB < 5){
habitat<-c("Habitat Type 4")}
habitat
}
for(i in 1:n){
ind.hab<-hab.assign()
hab.units[i]<-ind.hab
}
hab.units
}
It will still of course output a meaningful answer if I give it just one sample, but the full vectors give me an error message:
Warning message: In if (HabA < 5 & HabB < 5) { : the condition has length > 1 and only the first element will be used
Does anyone know how to get past this particular hurdle?