Using ifelse in R

前端 未结 2 1200
慢半拍i
慢半拍i 2020-12-07 04:32

I am trying to code the following statement in R with if and ifelse.The sample data is trial and x,y,and z are columns of trial).

S

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 05:27

    If you want to use ifelse and nest things you could do something like this

    test <- data.frame(x = 2, y = 5, z = 3)
    with(test, ifelse(z > 0 & x > 0 | y > 3, "yes", "no"))
    

    In this case you're using logical operators to guard the output. You'll still get "no" if z <= 0, but you can deal with that pretty easily.

    with(test, ifelse(z > 0, ifelse(x > 0 | y > 3, "yes", "no"), NA))
    

    Nested ifelse statements can get hard to follow in any language, so consider matching or switch statements if you end up with more than 3 of them.

提交回复
热议问题