CarlAH
CarlAH

Reputation: 217

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?

Upvotes: 5

Views: 154

Answers (1)

talat
talat

Reputation: 70296

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.

Upvotes: 7

Related Questions