Home > OS >  How to adopt ifelse statement to NA value in R?
How to adopt ifelse statement to NA value in R?

Time:05-17

I am trying to create new column by condition, where if value in A equal to 1, value is copied from B column, otherwise from C column. When A has NA, condition does not work. I dont want to drop this NA and do following: If A contains NA, values has to taken from C column

df <- data.frame (A  = c(1,1,NA,2,2,2),
                  B = c(10,20,30,40,25,45),
                  C = c(11,23,33,45,56,13))


#If Customer faced defect only in Wave_3 his Boycotting score is taken from wave 3, otherwise from wave 4
df$D1 <- ifelse(df$A ==1 , df$B ,df$C)

Expected output:

enter image description here

CodePudding user response:

Use Boolean operation here:

df$D1 <- ifelse(df$A ==1 & !is.na(df$A), df$B ,df$C)

alternate way is

df$D1 <- ifelse(is.na(df$A), df$C, ifelse(df$A ==1 , df$B ,df$C))

CodePudding user response:

Same idea as @Mohanasundaram, but implemented in dplyr chain:

library(dplyr)
df %>%
  mutate(D1 = ifelse(A == 1 & !is.na(A), B, C))

Output:

   A  B  C D1
1  1 10 11 10
2  1 20 23 20
3 NA 30 33 33
4  2 40 45 45
5  2 25 56 56
6  2 45 13 13

CodePudding user response:

Using case_when

library(dplyr) 
df %>%
   mutate(D1 = case_when(A %in% 1 ~ B, TRUE ~ C))
   A  B  C D1
1  1 10 11 10
2  1 20 23 20
3 NA 30 33 33
4  2 40 45 45
5  2 25 56 56
6  2 45 13 13
  • Related