通常 ifelse 需要 3 个参数(测试,是,否):
ifelse(c(1,2) == 1, T, F)
仅提供测试参数会导致错误(因为没有默认的 yes 或 no 字段):
ifelse(c(1,2) == 1)
在 magrittr 中使用时,ifelse 在仅接收测试参数时工作正常:
c(1:2) %>% ifelse(. == 1)
谁能解释为什么第三段代码可以正常工作,但第二段代码会出错?
# the standard use
ifelse(c(1,2) == 1, T, F) # [1] TRUE FALSE
# here it crashes because 1st argument is FALSE for 2 and there's no `no` argument
ifelse(c(1,2) == 1, T) # Error in ifelse(c(1, 2) == 1, T) : argument "no" is missing, with no default
# but `no` is not needed if the test is always TRUE
ifelse(c(1,1) == 1, T) # [1] TRUE TRUE
# These are equivalent,
library(magrittr)
c(1:2) %>% ifelse(. == 1) # [1] TRUE FALSE
c(1:2) %>% ifelse(.,. == 1) # [1] TRUE FALSE
# the dot is a vector of non-zero numeric so it evaluates to TRUE both times, the value returned is `yes`, and that is
c(1:2) == 1 # [1] TRUE FALSE