Livia
Livia

Reputation: 11

Ifelse statements chain for creating a new column based on some conditions of other columns

My participants were asked a question (cle1i2) with possible answers yes (1) or no (0).

Among these, who replied yes, were again asked another question (cle2i2), with yes (1) or no (0) possible answers.

Now, in R, I would like to create a new column (cle7_P), with values in it depending on the following conditions.

The conditions are these ones, and should be implemented all together;

  1. IF cle1i2 is NA AND cle2i2 is NA, THEN cle7_P is NA;

  2. IF cle1i2 is 0 AND cle2i2 is NA, THEN cle7_P is 0;

  3. IF cle1i2 is 1 AND cle2i2 is 1, THEN cle7_P is 1;

  4. IF cle1i2 is 1 AND cle2i2 is 0, THEN cle7_P is 0;

  5. IF cle1i2 is 1 AND cle2i2 is NA, THEN cle7_P is NA;

This is what I have tried so far, but it does not work when I check manually the data.

library(dplyr)
library(tidyverse)

h$pcle7_P %>% 
  (ifelse(is.na( cle1i2) & is.na( cle2i2), 
       yes = NA, 
       no = ifelse( cle1i2 == 0 & is.na( cle2i2), 
          yes = 0, 
          no = ifelse( cle1i2 == 1 & cle2i2 == 1, 
              yes = 1, 
              no = ifelse( cle1i2 == 1 & cle2i2 == 0, 
                  yes = 0, 
                  no = ifelse( cle1i2 == 1 & is.na(cle2i2), 
                      NA))))))



h <- h %>%
  mutate( pcle7_P = ifelse(cle1i2 == NA | cle2i2 == NA, 
    yes = NA, 
    no = ifelse(cle1i2 == 0 | cle2i2 == NA, 
        yes =0, 
        no = ifelse(cle1i2 == 1 | cle2i2 == 1, 
            yes = 1, 
            no = ifelse(cle1i2 == 1 | cle2i2 == 0, 
                yes = 0, 
                no = ifelse(cle1i2 == 1 | cle2i2 == NA), 
                    NA)))))

I would expect a new column with values according to the conditions.

Can you help me? Thank you

Upvotes: 1

Views: 72

Answers (2)

AmyM
AmyM

Reputation: 22

Your second attempt could work, but remember

> NA == NA
[1] NA

You needed to use is.na(cle1i2) as you did in your first attempt.

Upvotes: 0

Roman
Roman

Reputation: 17648

You can try case_when which is perfect for multiple ifelse

library(tidyverse)
h %>% 
  mutate(pcle7_P = case_when(is.na(cle1i2) & is.na(cle2i2) ~ NA_real_,
                             cle1i2 == 0 ~ 0,
                             cle1i2 == 1 & cle2i2 == 1 ~ 1,
                             cle1i2 == 1 & cle2i2 == 0 ~ 0, 
                             cle1i2 == 1 & is.na(cle2i2) == 1 ~ NA_real_))

Upvotes: 2

Related Questions