Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the ternary operator exist in R?

Tags:

operators

r

As the question asks, is there a control sequence in R similar to C's ternary operator? If so, how do you use it? Thanks!

like image 575
eykanal Avatar asked Jan 09 '12 14:01

eykanal


People also ask

What is R ternary operator?

The ternary operator is an operator that exists in some programming languages, which takes three operands rather than the typical one or two that most operators use. It provides a way to shorten a simple if else block.

Why we should not use ternary operator?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.

Does ternary operator exist in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");

Does Go have the ?: operator?

No Go doesn't have a ternary operator, using if/else syntax is the idiomatic way.


1 Answers

As if is function in R and returns the latest evaluation, if-else is equivalent to ?:.

> a <- 1 > x <- if(a==1) 1 else 2 > x [1] 1 > x <- if(a==2) 1 else 2 > x [1] 2 

The power of R is vectorization. The vectorization of the ternary operator is ifelse:

> a <- c(1, 2, 1) > x <- ifelse(a==1, 1, 2) > x [1] 1 2 1 > x <- ifelse(a==2, 1, 2) > x [1] 2 1 2 

Just kidding, you can define c-style ?::

`?` <- function(x, y)     eval(       sapply(         strsplit(           deparse(substitute(y)),            ":"       ),        function(e) parse(text = e)     )[[2 - as.logical(x)]]) 

here, you don't need to take care about brackets:

> 1 ? 2*3 : 4 [1] 6 > 0 ? 2*3 : 4 [1] 4 > TRUE ? x*2 : 0 [1] 2 > FALSE ? x*2 : 0 [1] 0 

but you need brackets for assignment :(

> y <- 1 ? 2*3 : 4 [1] 6 > y [1] 1 > y <- (1 ? 2*3 : 4) > y [1] 6 

Finally, you can do very similar way with c:

`?` <- function(x, y) {   xs <- as.list(substitute(x))   if (xs[[1]] == as.name("<-")) x <- eval(xs[[3]])   r <- eval(sapply(strsplit(deparse(substitute(y)), ":"), function(e) parse(text = e))[[2 - as.logical(x)]])   if (xs[[1]] == as.name("<-")) {     xs[[3]] <- r         eval.parent(as.call(xs))   } else {     r   } }        

You can get rid of brackets:

> y <- 1 ? 2*3 : 4 > y [1] 6 > y <- 0 ? 2*3 : 4 > y [1] 4 > 1 ? 2*3 : 4 [1] 6 > 0 ? 2*3 : 4 [1] 4 

These are not for daily use, but maybe good for learning some internals of R language.

like image 161
kohske Avatar answered Sep 19 '22 18:09

kohske