Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with TRUE, FALSE, NA and NaN

Here is a vector

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

I'd like a simple function that returns TRUE everytime there is a TRUE in "a", and FALSE everytime there is a FALSE or a NA in "a".

The three following things do not work

a == TRUE identical(TRUE, a) isTRUE(a) 

Here is a solution

a[-which(is.na(a))] 

but it doesn't seem to be a straightforward and easy solution

Is there another solution ?

Here are some functions (and operators) I know:

identical() isTRUE() is.na() na.rm() & | ! 
  • What are the other functions (operators, tips, whatever,...) that are useful to deal with TRUE, FALSE, NA, NaN?

  • What are the differences between NA and NaN?

  • Are there other "logical things" than TRUE, FALSE, NA and NaN?

Thanks a lot !

like image 309
Remi.b Avatar asked May 29 '13 19:05

Remi.b


People also ask

Is true && true false?

The && and || Operators in JavaScript. If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).

What does Na true evaluate to?

In other words NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE.

Why is True False 1?

In programming languages value of True is considered as 1. whereas false is zero. therefore In Boolean algebra True + False=1+0=1.

Is NA function in R?

The is.na() is a built-in R function that returns TRUE if it finds NA value and FALSE if it does not find in the dataset. If the value is NA, the is.na() function returns TRUE, otherwise, returns FALSE.


2 Answers

You don't need to wrap anything in a function - the following works

a = c(T,F,NA)  a %in% TRUE  [1]  TRUE FALSE FALSE 
like image 99
wjchulme Avatar answered Oct 04 '22 19:10

wjchulme


To answer your questions in order:

1) The == operator does indeed not treat NA's as you would expect it to. A very useful function is this compareNA function from r-cookbook.com:

  compareNA <- function(v1,v2) {     # This function returns TRUE wherever elements are the same, including NA's,     # and false everywhere else.     same <- (v1 == v2)  |  (is.na(v1) & is.na(v2))     same[is.na(same)] <- FALSE     return(same)    } 

2) NA stands for "Not available", and is not the same as the general NaN ("not a number"). NA is generally used for a default value for a number to stand in for missing data; NaN's are normally generated because a numerical issue (taking log of -1 or similar).

3) I'm not really sure what you mean by "logical things"--many different data types, including numeric vectors, can be used as input to logical operators. You might want to try reading the R logical operators page: http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html.

Hope this helps!

like image 30
ben Avatar answered Oct 04 '22 19:10

ben