通常,ifelse需要3个参数(test,yes,no):
ifelse(c(1,2) == 1, T, F)
仅提供测试参数会导致错误(因为没有默认的yes或no字段):
ifelse(c(1,2) == 1)
在magrittr中使用时,ifelse仅在收到测试参数时工作正常:
c(1:2) %>% ifelse(. == 1)
任何人都可以解释为什么第三块代码工作正常,但第二块会导致错误吗?
答案 0 :(得分:0)
# 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