Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k 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
edited by

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

Related questions

0 votes
3 answers
asked Jul 19, 2019 in R Programming by Ajinkya757 (5.3k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...