Conditional assignment with NA value

test <- data.frame(
  stringsAsFactors = FALSE,
        CaseNumber = c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22),
            TERMNB = c("1", "2", NA, "3", "3", "3", "3", "1", "1", "1", "1", NA),
       BIRTHWEIGHT = c(3200,3200,3200,3200,3000,
                       2900,NA,3200,3200,3200,3200,NA)
)

# codes want to assign new variable mca based on these conditions  
df1 <- test %>% 
  mutate(mca='') %>% 
  mutate(mca=ifelse(is.na(TERMNB) & is.na(BIRTHWEIGHT)==TRUE,'X',mca)) %>% 
  mutate(mca=ifelse(nchar(mca)==0 & TERMNB==2,'B',mca)) 
# casenumber 12 mca as expected B. casenumber 22 as expected X.  Why the casenumber 13 mca became NA? Im expecting nothing

df2 <- df1 %>% 
  mutate(mca=ifelse(nchar(mca)==0 & TERMNB==3 & BIRTHWEIGHT<3000,'B',mca))

#casenumber 16 mca as expected B. why the casenumber 17 mca became NA? Im expecting nothing



df3 <- df2 %>% 
  mutate(mca=ifelse(nchar(mca)==0 & TERMNB==3 & is.na(BIRTHWEIGHT)==TRUE,'X',mca))

# casenumber 17 mca should be X,but it's NA why? How to fix these problems?  Thank you.

Hi @tjcnnl1. When testing for specific values in a column that has NA values, I find it helpful to include logic that explicitly states the column is not NA and is equal to the value (ie. !is.na(column) & column == x). I've added these checks below.

df1 <- test %>% 
  mutate(mca='') %>% 
  mutate(mca=ifelse(is.na(TERMNB) & is.na(BIRTHWEIGHT)==TRUE,'X',mca)) %>% 
  mutate(mca=ifelse(!is.na(mca) & nchar(mca)==0 & 
                      !is.na(TERMNB) & TERMNB==2,'B',mca)) 

df2 <- df1 %>% 
  mutate(mca=ifelse(!is.na(mca) & nchar(mca)==0 & 
                      !is.na(TERMNB) & TERMNB==3 & 
                      !is.na(BIRTHWEIGHT) & BIRTHWEIGHT<3000,'B',mca))


df3 <- df2 %>% 
  mutate(mca=ifelse(!is.na(mca) & nchar(mca)==0 & 
                      !is.na(TERMNB) & TERMNB==3 & 
                      is.na(BIRTHWEIGHT)==TRUE,'X',mca))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.