0

Normally ifelse requires 3 arguments (test, yes, no):

ifelse(c(1,2) == 1, T, F)

Providing only a test argument results in an error (because there is no default yes or no field):

ifelse(c(1,2) == 1)

When used in magrittr, ifelse works fine when only receiving a test argument:

c(1:2) %>% ifelse(. == 1)

Can anyone explain why the third chunk of code works fine, but the second results in an error?

rawr
  • 20,481
  • 4
  • 44
  • 78
shackett
  • 323
  • 2
  • 5
  • 2
    `c(1,2)` _is_ the "test" `. == 1` is passed to "yes". since `as.logical(1:2)` is always true, the "no" is never evaluated, eg, `c(1:2) %>% ifelse(. == 1, simpleError())` or try `c(0:2) %>% ifelse(. == 1)` – rawr Feb 24 '16 at 03:06
  • @rawr, post as answer? – Ben Bolker Feb 24 '16 at 03:11
  • @BenBolker smells like this [q](http://stackoverflow.com/questions/16275149/does-ifelse-really-calculate-both-of-its-vectors-every-time-is-it-slow) – rawr Feb 24 '16 at 03:13
  • Thanks for clarifying @rawr, it seems like it was just a weird bug in the end. Chunk 3 is really evaluating `ifelse(c(1:2), c(1:2) == 1)` – shackett Feb 24 '16 at 03:27

1 Answers1

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
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167