0

So I have this vector:

Kc167 <- c(7.333333, 24.666667, 31.333333, 65.000000, 59.666667, 74.333333, 72.000000, 38.333333, 73.666667, 87.333333)

and I want to categorise each of those numbers into "low", "medium", or "high".

I've written a function that can categorise any number into those categories:

getExpressionLevel <- function(x){
if (x < 5)
return ("none")
else if (x == 5)
return ("low")
else if (x > 5 & x < 20)
return ("low")
else if (x == 20)
return ("medium")
else if (x > 20 & x < 60)
return("medium")
else if (x > 60)
return("high")
}

I've checked that the function works:

getExpressionLevel(55.4)
[1] "medium"

But when I try to use the function on the vector Kc167, it doesn't seem to work:

getExpressionLevel(Kc167)
[1] "low"
Warning messages:
1: In if (x < 5) return("none") else if (x == 5) return("low") else if (x    >  :
  the condition has length > 1 and only the first element will be used
2: In if (x == 5) return("low") else if (x > 5 & x < 20) return("low") else if (x ==  :
  the condition has length > 1 and only the first element will be used
3: In if (x > 5 & x < 20) return("low") else if (x == 20) return("medium") else if (x >  :
  the condition has length > 1 and only the first element will be used

I've looked around and the ifelse statement works:

ifelse(Kc167>60, "high", "low")
[1] "low"  "low"  "low"  "high" "high" "high" "high" "low"  "high" "high"

But I'm not sure how to add all the remaining conditions into that statement, and why my original function/if... else statement didn't work. Is there something I'm forgetting to add?

Hola
  • 1
  • 1
  • `getEL <- Vectorize(getExpressionLevel); getEL(Kc167)` or `sapply(Kc167, getExpressionLevel)` – jogo Feb 28 '18 at 13:31
  • 1
    See also [Convert continuous numeric values to discrete categories defined by intervals](https://stackoverflow.com/questions/13559076/convert-continuous-numeric-values-to-discrete-categories-defined-by-intervals), i.e. check `cut` and `findInterval`. – Henrik Feb 28 '18 at 13:36
  • omg thank you, that makes so much sense! – Hola Feb 28 '18 at 13:38

0 Answers0