1

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
tall_table
  • 311
  • 3
  • 11
  • 1
    Given your example, you don't really need an `ifelse` statement, you could do `mutate(var3=pmax(var1,var2,na.rm=T))` or `mutate(var3=coalesce(var1,var2))`. – Lamia Sep 03 '17 at 19:59

2 Answers2

5

Just to explain why your version does not work: NA == NA is not TRUE, it's NA - conceptually this makes sense, usually we want to know if two values are the same, and if we don't know one or both of them, we don't know of they are the same or not. To test if a value is NA you need to use the function is.NA(). Here's a simple version:

df_addvar3 <- df %>%
  mutate(var3 = ifelse(is.na(var1), var2, var1))

Your question was not quite clear what you want to happen if the values are different from -1:1, or if var1 and var2 are both not NA, but different from one another. All of these should be relatively simple to add if necessary.

Christoph Wolk
  • 1,748
  • 1
  • 7
  • 12
0
replace(x = df[cbind(1:NROW(df), max.col(replace(df, is.na(df), -Inf)))],
        list = rowSums(is.na(df)) == NCOL(df),
        values = NA)
#[1]  1  1 NA -1  0
d.b
  • 32,245
  • 6
  • 36
  • 77