R中多个ifelse的替代方案

时间:2014-01-14 12:24:33

标签: r if-statement

我对ifelse中的多个R语句感到厌倦。我知道有一个名为switch的函数,但如果以下示例,则无法弄清楚如何使用。

set.seed(12345)
Y <- runif(n=100, min=0, max=50)

ifelse(
    test = Y < 5
  , yes  = "A"
  , no   =  ifelse(
         test = Y < 10
       , yes  = "B"
       , no = "C"
       )
    )

输出


  [1] "C" "C" "C" "C" "C" "B" "C" "C" "C" "C" "A" "B" "C" "A" "C" "C" "C" "C"
 [19] "B" "C" "C" "C" "C" "C" "C" "C" "C" "C" "C" "C" "C" "A" "B" "C" "C" "C"
 [37] "C" "C" "C" "B" "C" "C" "C" "C" "C" "C" "A" "A" "A" "C" "C" "C" "C" "C"
 [55] "C" "C" "C" "A" "C" "C" "C" "C" "C" "C" "C" "C" "C" "B" "C" "C" "C" "C"
 [73] "C" "C" "A" "C" "C" "C" "C" "B" "C" "C" "A" "A" "B" "C" "C" "C" "C" "A"
 [91] "C" "C" "A" "C" "C" "C" "C" "C" "A" "C"

任何帮助都将受到高度赞赏。感谢


被修改


如果我有以下代码。那么ifelse语句的更好选择是什么。

set.seed(12345)
Y <- runif(n=100, min=0, max=50)

ifelse(
    test = Y < 5
  , yes  = -5
  , no   =  ifelse(
         test = Y < 10
       , yes  = 0
       , no = 5
       )
    )

2 个答案:

答案 0 :(得分:8)

switch并不是真的意味着这样的事情,cut更好:

cut(Y,c(-Inf,5,10,Inf),labels=LETTERS[1:3],right=FALSE)
  [1] C C C C C B C C C C A B C A C C C C B C C C C C C C C C C C C A B C C C C
 [38] C C B C C C C C C A A A C C C C C C C C A C C C C C C C C C B C C C C C C
 [75] A C C C C B C C A A B C C C C A C C A C C C C C A C
Levels: A B C

答案 1 :(得分:1)

这是基于逻辑和数学运算的一种方式(解决你的编辑问题):

5 * ((Y >= 10) - (Y < 5))

 [1]  5  5  5  5  5  0  5  5  5  5 -5  0  5 -5  5  5  5  5  0  5  5  5
[23]  5  5  5  5  5  5  5  5  5 -5  0  5  5  5  5  5  5  0  5  5  5  5
[45]  5  5 -5 -5 -5  5  5  5  5  5  5  5  5 -5  5  5  5  5  5  5  5  5
[67]  5  0  5  5  5  5  5  5 -5  5  5  5  5  0  5  5 -5 -5  0  5  5  5
[89]  5 -5  5  5 -5  5  5  5  5  5 -5  5