我熟悉写ifelse()
条语句,它们非常有用,但是当它们有多个条件时,它们似乎非常低效.我很好奇是否有更有效的方法来写它们.例如,如果我有下面的 struct
test <- data.frame(col = c("a", "b", "c", "d", "e"))
test$col <- factor(test$col)
col
1 a
2 b
3 c
4 d
5 e
我可以写
test$col2 <- ifelse(test$col == "a" | test$col == "b" | test$col == "c", "x", "z")
test
col col2
1 a x
2 b x
3 c x
4 d z
5 e z
在这里,我基本上已经在Oifelse()
语句中写了三次相同的东西(test$col ==
).我如何编写代码才能使我只输入test$col ==
一次?
我承认下面的说法是不正确的,也不起作用,但我对这样的事情的猜测是
test$col2 <- ifelse(test$col == c("a", "b", "c"), "x", "z")
OR
test$col2 <- ifelse(test$col == "a" | "b" | "c", "x", "z")
多次编写代码test$col ==
是低效的.在这样的ifelse()
声明中,这是可以避免的吗?