Does the ternary operator exist in R?

后端 未结 7 1210
日久生厌
日久生厌 2020-12-22 16:52

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!

相关标签:
7条回答
  • 2020-12-22 17:40

    Just as a prank, you can redefine the ? operator to (almost) work like the ternary operator (THIS IS A BAD IDEA):

    `?` <- function(x, y) { y <-substitute(y); if(x) eval(y[[2]], parent.frame()) else eval(y[[3]], parent.frame()) }
    
    x <- 1:3
    length(x) ? (x*2) : 0
    x <- numeric(0)
    length(x) ? (x*2) : 0
    
    for(i in 1:5) cat(i, (i %% 2) ? "Odd\n" : "Even\n")
    

    ... But you need to put the expressions in parentheses because the default precedence isn't like in C.

    Just remember to restore the old help function when you're done playing:

    rm(`?`)
    
    0 讨论(0)
提交回复
热议问题