如何使用带有多个矢量条件的if..else语句?

时间:2018-02-28 13:29:15

标签: r

所以我有这个载体:

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

我希望将每个数字分类为“低”,“中”或“高”。

我写了一个函数,可以将任何数字分类到这些类别中:

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")
}

我已经检查过该功能是否有效:

getExpressionLevel(55.4)
[1] "medium"

但是当我尝试在矢量Kc167上使用该功能时,它似乎不起作用:

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

我环顾四周,ifelse声明有效:

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

但我不确定如何将所有剩余条件添加到该语句中,以及为什么我的原始函数/ if ... else语句不起作用。有什么我忘记添加的吗?

0 个答案:

没有答案