0 votes
1 view
in R Programming by (5.2k points)

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!

1 Answer

0 votes
by (25.3k points)

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...