Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorized OR function that evaluates FALSE | NA and NA | FALSE as FALSE?

Given the vectors:

vect1 <- c(TRUE,FALSE,FALSE,NA,NA,NA,TRUE,FALSE,NA,FALSE)
vect2 <- c(TRUE,NA,FALSE,NA,FALSE,TRUE,FALSE,NA,TRUE,NA)
vect3 <- vect1 | vect2
vect3 #c(TRUE,NA,FALSE,NA,NA,TRUE,TRUE,NA,TRUE,NA)

Is there a vectorized infix function x that evaluates elements like this:

TRUE x TRUE #TRUE
TRUE x FALSE #TRUE
FALSE x TRUE #TRUE
FALSE x FALSE #FALSE
TRUE x NA #TRUE
NA x TRUE #TRUE
FALSE x NA #FALSE - would have been NA with ordinary "|"
NA x FALSE #FALSE - would have been NA with ordinary "|"
NA x NA #NA

Producing a vector vect4 like this:

vect4 #c(TRUE,FALSE,FALSE,NA,FALSE,TRUE,TRUE,FALSE,TRUE,FALSE)

Or is there any other simple method to output vect4 from vect1 and vect2?

like image 735
CarlAH Avatar asked Dec 12 '15 17:12

CarlAH


1 Answers

You can compute the paralell maximum (with na.rm = TRUE) and convert to logical:

as.logical(pmax(vect1, vect2, na.rm = TRUE))
# [1]  TRUE FALSE FALSE    NA FALSE  TRUE  TRUE FALSE  TRUE FALSE

Note that by computing maxima of logical vectors, TRUE is interpreted as integer 1 and FALSE as integer 0.

like image 172
talat Avatar answered Nov 15 '22 23:11

talat