Does the ternary operator exist in R?

后端 未结 7 1208
日久生厌
日久生厌 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:21

    Your link points to an if statement.

    > x <- 1
    > if(x < 2) print("Less than") else print("Greater than")
    [1] "Less than"
    

    If your input variable is a vector, then ifelse might be more suitable:

    > x <- 1:3
    > ifelse(x<=2, "Less than or equal", "Greater than")
    [1] "Less than or equal" "Less than or equal" "Greater than"   
    

    To access the help page for if, you need to embed the if in backticks:

    ?`if`
    

    The help page for ifelse is at:

    `?ifelse`
    

提交回复
热议问题