dimanche 3 septembre 2017

How to handle NAs in ifelse when creating new column

Goal: Evaluate two separate columns, var1 and var2 below, with ifelse statements to create a third, composite column, var3 below. For instance, I want to check for each column and if they both contain NA, I need NA in the third column, var3. If var1 or var2 contains -1, 0, or 1, I would like that to be in var3

Issue: Turns up all NAs. I know there is some silly issue with evaluating the NAs, but I am missing it.

Desired output:

var1  var2  var3
  1    NA    1
  NA   1     1
  NA   NA    NA
  NA   -1    -1
  0    NA    0

Reproducible example:

library(tidyverse)

df <- data.frame(var1 = c(1, 1, NA, NA, 0),
                  var2 = c(NA, 1, NA, -1, NA))

df_addvar3 <- df %>%
    mutate(var3 = ifelse(var1 == NA | var2 == NA, NA,
                      ifelse(var1 == -1 | var2 == -1, -1,
                          ifelse(var1 == 0 | var2 == 0, 0,
                              ifelse(var1 == 1 | var2 == 1, 1, NA)))))

df_addvar3

Aucun commentaire:

Enregistrer un commentaire