Why TRUE == “TRUE” is TRUE in R?

前端 未结 3 620
无人及你
无人及你 2020-11-29 05:29
  1. Why TRUE == \"TRUE\" is TRUE in R?
  2. Is there any equivalent for === in R?

Update:

<
3条回答
  •  猫巷女王i
    2020-11-29 06:24

    TRUE and FALSE are reserved words in R. I don't think eznme was correct (before his edit) when he said any non-zero value was TRUE, since TRUE == "A" evaluates to FALSE. (That would have been correct in explaining why TRUE == 1 evaluates to TRUE, but it would not explain the result for TRUE == 7

    The explanation given by plannapus was taken out of the context of describing the behavior of as.logical. It is closer to the "truth", because it is the implicit coercion of TRUE to character by the == operator that creates this result. Although T and F are initially given the values of TRUE and FALSE, they can be reassigned to other values or types.

    > TRUE == as.logical( c("TRUE", "T", "true", "True") )
    [1] TRUE TRUE TRUE TRUE
    
    >  TRUE == 7
    [1] FALSE
    > TRUE == as.logical(7)
    [1] TRUE
    >  TRUE == as.logical("A")
    [1] NA
    

    (I earlier incorrectly wrote that the coercion induced by TRUE == "TRUE" was to logical; it's actually via as.character(TRUE) returning "TRUE".)

提交回复
热议问题