2

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?

4

1 に答える 1

5

多分

hab.assign <- function(HabA,HabB){
  ifelse(HabA < 5 & HabB < 5,
            "Habitat Type 1",
   ifelse(HabA > 5 & HabB < 5,
            "Habitat Type 2",
   ifelse(HabA < 5 & HabB > 5,
            "Habitat Type 3",
   ifelse(HabA < 5 & HabB < 5,
            "Habitat Type 4","weird habitat"))))
}

この特定の問題については、おそらく、組み合わせに基づいて整数コードを導出することに基づいた、より賢い/より高速なソリューションがあります。

code <- 1+as.numeric(habA>5)+as.numeric(habB>5)*2

両方の生息地 <= 5 では 1、habA<=5とでは 2 などと評価さhabB>5れます。その後、switchステートメントを使用してコードを割り当てるか、それに応じて因子の水準を割り当てることができます。しかし、ifelseアプローチはおそらくより読みやすいです。

于 2013-01-12T18:57:44.793 に答える