Home > other >  Classify a variable depending on the number of NAs in R
Classify a variable depending on the number of NAs in R

Time:02-04

I have 2 scenarios:

  • One where I would like to define a new variable (called df$x1) depending on whether there are 16 NAs in 16 other different columns. My proposed code would be:

    cols <- 1:16

    df %>% mutate(x1=ifelse(rowSums(df[cols] ==NA, na.rm = TRUE) ==16) ,'Yes', 'No')))

  • On the second scenario, I would like to check whether there is at least 1 NA in a list of 12 variables

How would you do that?

Thank you!

CodePudding user response:

Continuing with your 1st approach except NA's are checked with is.na -

cols <- 1:12

df$x1 <- ifelse(rowSums(is.na(df[cols])) > 0, 'Yes', 'No')

CodePudding user response:

1s't Scenario: df$x1 <- ifelse(rowSums(is.na(df[,cols])) == 16, "Yes", "No")

  • Related