Logical condition while subsetting not giving correct values

前端 未结 1 1553
耶瑟儿~
耶瑟儿~ 2021-01-28 18:20

I wanted to subset data frame project I was working with, using a logical. I am getting a paradoxical result. The part of the logical preceding the ROLL.NO.

相关标签:
1条回答
  • 2021-01-28 18:50

    From ?base::Logic, help('&'), help('|'), etc

    See Syntax for the precedence of these operators: unlike many other languages (including S) the AND and OR operators do not have the same precedence (the AND operators have higher precedence than the OR operators).

    which explains why

    TRUE | TRUE & FALSE
    # [1] TRUE
    

    which is essentially

    TRUE | (TRUE & FALSE)
    

    which is also true, and a simplification of what you are doing here:

    (project$DC31==1&project$D14==2) |
      (project$DC31==2&project$D14==1) &
      !is.na(project$DC31) &
      !is.na(project$D14) &
      project$ROLL.NO. == 3131
    

    since you expect the result only to contain some project$ROLL.NO. == 3131 I assume, so even if some of these are false, if one or more OR is true, you may get some that are not ROLL.NO. which are not 3131

    Also note that ! has a higher precedence than logicals

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