我厌倦了在R中使用多个ifelse
语句。我知道有一个名为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
)
)
?cut
。 - Dasontest, yes, no
。实际上,它们并不必要,可以使用ifelse(Y<5,"A",ifelse(Y<10, "B","C"))
这样的语句替代。 - flodelcut
的概念,还可以参考?findInterval
。如果符合您的需求,它可能会更快,因为它产生的输出比cut
不太“整洁”。LETTERS[findInterval(Y, c(-Inf, 5, 10, Inf))]
。 - alexis_lazfindInterval(Y,c(5,10))
就足够了(不需要无穷大),尽管需要一个+1
来将它们转换为正确的索引进入LETTERS
。 - user295691