简体   繁体   English

关于 R 中 3 个条件的 if 语句

[英]if statement on 3 conditions in R

I see some issues in my if statement.我在 if 语句中看到了一些问题。 The output I get is wrong than what i expected.我得到的 output 比我预期的要错。

asd <- data.frame(a = c(-16,-9,-48,20,-39), b = c(2, -4, -2, 2, 4), c = c(9, -14, 23, -13, -6))
if(asd$a < 0 && asd$b>0 && asd$c>0){
  asd$d <- "Inv"
} else {
  asd$d <- "NotInv"
}
> asd
    a  b   c   d
1 -16  2   9 Inv
2  -9 -4 -14 Inv
3 -48 -2  23 Inv
4  20  2 -13 Inv
5 -39  4  -6 Inv

Expected output预期 output

> asd
    a  b   c   d
1 -16  2   9 Inv
2  -9 -4 -14 Not Inv
3 -48 -2  23 Not Inv
4  20  2 -13 Not Inv
5 -39  4  -6 Not Inv

with base R :带底座R

asd$d <- "Not Inv"
asd$d[asd$a < 0 & asd$b>0 & asd$c>0] <- "Inv"
asd

    a  b   c       d
1 -16  2   9     Inv
2  -9 -4 -14 Not Inv
3 -48 -2  23 Not Inv
4  20  2 -13 Not Inv
5 -39  4  -6 Not Inv

with dplyr :dplyr

library(dplyr)
asd %>% mutate(d = if_else(a < 0 & b>0 & c>0,"Inv","Not Inv"))

    a  b   c       d
1 -16  2   9     Inv
2  -9 -4 -14 Not Inv
3 -48 -2  23 Not Inv
4  20  2 -13 Not Inv
5 -39  4  -6 Not Inv

You got a wrong result because you used && instead of & :您得到了错误的结果,因为您使用&&而不是&

asd$a < 0 && asd$b>0 && asd$c>0
[1] TRUE

Meaning that only if statement is executed:意味着只有if语句被执行:

asd$d <- "Inv"

Using & instead gives the expected vectorized result:使用&代替给出预期的矢量化结果:

asd$a < 0 & asd$b>0 & asd$c>0
[1]  TRUE FALSE FALSE FALSE FALSE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM