Dealing with TRUE, FALSE, NA and NaN

后端 未结 5 560
萌比男神i
萌比男神i 2020-11-27 17:15

Here is a vector

a <- c(TRUE, FALSE, FALSE, NA, FALSE, TRUE, NA, FALSE, TRUE)

I\'d like a simple function that returns TRUE

5条回答
  •  鱼传尺愫
    2020-11-27 18:19

    Taking Ben Bolker's suggestion above you could set your own function following the is.na() syntax

    is.true <- function(x) {
      !is.na(x) & x
    }
    
    a = c(T,F,F,NA,F,T,NA,F,T)
    
    is.true(a)
    [1]  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE
    

    This also works for subsetting data.

    b = c(1:9)
    df <- as.data.frame(cbind(a,b))
    
    df[is.true(df$a),]
    
      a b
    1 1 1
    6 1 6
    9 1 9
    

    And helps avoid accidentally incorporating empty rows where NA do exist in the data.

    df[df$a == TRUE,]
    
          a  b
    1     1  1
    NA   NA NA
    6     1  6
    NA.1 NA NA
    9     1  9
    

提交回复
热议问题