conditional statements with missing values

Viewed 53

total Julia beginner here, coming from R. I am struggling to find a simple syntax to define a new variable based on two variables that have missing values. Suppose I have two variables in R as follows:

esi_offer_cps <- esi_own <- rep(NA,100)
esi_offer_cps[1:25] <- 0
esi_offer_cps[26:50] <- 1 
esi_own[1:16] <- 0
esi_own[25:40] <- 0
esi_own[51:62] <- 0
esi_own[63:80] <- 1

t1 <- table(esi_offer_cps, esi_own, exclude=NULL)
print(t1)

              esi_own
esi_offer_cps  0  1 <NA>
         0    17  0    8
         1    15  0   10
         <NA> 12 18   20

In R I define a new variable as follows:


esi_offer <- ifelse(esi_offer_cps | (!is.na(esi_own) & esi_own == 1),1,0)

t2 <- table(esi_offer, exclude=NULL)
print(t2)

   esi_offer
   0    1 <NA> 
  25   43   32 

The 43 records with esi_offer = 1 come from the sum of 15+10+18, and the 25 records with value 0 come from 17+8. This works in R because features such as NA | T = T and NA & F = F work when vectorized. In Julia I understand I can't have Boolean statements with .&& or .|| where missing values are present, and I am going nuts looking for some reasonable way to deal with cases like this in base Julia. performance is not my worry at the moment (one thing at the time!). I understand that if these are columns of data frames there might ways specific to dataframes, but I have not investigated those because I am trying to understand the basics.
I have been exploring the use of ismissing, ternary operators and bitwise operators, but I think I am missing the big picture: there must be some principled way to look at operations of this type but I can't fathom it. If you can point to me to an article or a basic book with examples I would be grateful (or give me an example of how to deal with his particular case, hopefully I can extrapolate from that). I am still at the stage where reading the manual is not illuminating yet. Thank you in advance for your patience.

1 Answers

As August notes the && and || operators in Julia are strict, i.e. they require Bool as a first argument. Conversly & and | fully support 3-valued logic:

julia> [false, missing, true] .| [false missing true]
3×3 Matrix{Union{Missing, Bool}}:
 false             missing  true
      missing      missing  true
  true         true         true

julia> [false, missing, true] .& [false missing true]
3×3 Matrix{Union{Missing, Bool}}:
 false  false         false
 false       missing       missing
 false       missing   true

If you need some additional explanation of this please comment.

Related