?: operator in R


In c/c++ or some other languages, ?: operator is useful to describe conditional statement:

printf("%d", 1?2:3); // -> 2
printf("%d", 0?2:3); // -> 3

In R, however, we cannot use ?: operator by default (of course, I know the function ifelse() and also if-else statement can return value).

Inspired by the tweet on #rstats, here is the definition of that operator in R:

`?`<-function(C,V)do.call("ifelse",c(list(C),V))
`:`<-function(t,f)list(t,f)

then,

> 1?1:2
[1] 1

> 0?1:2
[1] 2

> c(1,0,1)?c(1,2,3):c(5,5,5)
[1] 1 5 3

This is just a kind of joke hack.
I strongly recommend you not to use this trick.
This overwrites the default definition of `:` and `?`.

If you have trouble after defining `:` and `?` above, please undefine them:

rm(':', '?')

Now you can use default ‘:’ and ‘?’.