?: 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 ‘?’.

3 thoughts on “?: operator in R

  1. Having read this I believed it was extremely enlightening.

    I appreciate you finding the time and energy to put this
    information together. I once again find myself personally
    spending a lot of time both reading and
    commenting. But so what, it was still worthwhile!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s