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!

0 votes

In R, the ternary operator as such, does not exist, but you can use the following to perform the same task as a ternary operator:

The **ifelse()** function:

a <- c(10,20,30)

x <- ifelse(a== 10, 10,20 )

x

[1] 10 20 20

x <- ifelse(a==20, 10, 20)

x

[1] 20 10 20

**Defining operators:**

You can also define c style ?: ternary operator as follows:

`?` <- function(x, y)

eval(

sapply(

strsplit(

deparse(substitute(y)),

":"

),

function(e) parse(text = e)

)[[2 - as.logical(x)]])

For example:

1 ? 5+5 : 5

[1] 10

FALSE ? 5*2 : 0

[1] 0

x <- (1 ? 5*5 : 8)

x

[1] 25