Reputation: 15
I have two variables (from a questionnaire): one is a score on a scale ranging from 1-5 (or NA) and one is a binary variable where people tick to indicate that a measure is "not applicable".
I want to take a tick in the 'not applicable' box (i.e. a '1' in Q17NA_1 in this example) as equivalent to '1' in the measurement variable (Q17_1).
For all other cases (i.e. where Q17NA_1 = NA), I want the outcome variable to be the same as Q17_1.
#======================================
library(tidyverse)
# create fictional data
data <- tibble (
Q17_1 = c(1, NA, NA, 1, 2, 3, NA, 2, NA),
Q17NA_1 = c(NA, 1, NA, 1, NA, 1, NA, 1, NA),
Q17_expected = c(1,1,NA,1,2,1,NA,1,NA)
)
# need to use the following rules to arrive at Q17_expected, but am not sure how to arrive at this result
# 1) If Q17_NA_1 = 1, then the outcome (Q17_expected) should be 1
# 2) If Q17_NA_1 = NA, then the outcome (Q17_expected) should be the value of (Q17_1)
#======================================
So the data look like this:
# A tibble: 9 x 3
Q17_1 Q17NA_1 Q17_expected
<dbl> <dbl> <dbl>
1 1 NA 1
2 NA 1 1
3 NA NA NA
4 1 1 1
5 2 NA 2
6 3 1 1
7 NA NA NA
8 2 1 1
9 NA NA NA
Based on a previous answer (How to combine 2 variables and ignore NAs) I tried the following:
data$Q17_expected2 <- ifelse(!is.na(data$Q17_1),data$Q17_1,data$Q17NA_1)
but it does not work correctly, as it is unable to force the first condition (i.e. that it the second column is 1, then the outcome should be 1).
Is there a straightforward way to do this?
Upvotes: 0
Views: 56
Reputation: 816
library(dplyr)
data %>% mutate(Q17_expected = coalesce(Q17NA_1, Q17_1))
Upvotes: 2