简体   繁体   中英

How to get R to ignore NA in ifelse statement

I've created a table for some model outputs, and have added a column for significance at the 0.05 level.

codominant_table$`Significance (Unadjusted)` <- ifelse(codominant_table$`Unadjusted Global p-value` >= 0.05 & !is.na(codominant_table$`Unadjusted Global p-value`), "Not Significant", "Significant")

codominant_table$`Significance (Adjusted)` <- ifelse(codominant_table$`Adjusted Global p-value` >= 0.05  & !is.na(codominant_table$`Adjusted Global p-value`), "Not Significant", "Significant")

For some reason, even though I've specified '!is.na(codominant_table$ Adjusted Global p-value )', the table still thinks that an 'NA' value is less than 0.05, and rates it as 'significant'. Here is the current table output:

表输出

Where, as you can see, the NAs in the Global p-value column is rated as 'significant'. How do I get R to ignore the NAs in an ifelse statement?

The conditional isn't evaluating the way you think. It should be "IF the p-value is >= 0.05 OR the pvalue IS missing THEN 'Not significant' ELSE 'Significant'."

Right now you have "IF the pvalue is >= 0.05 AND the value IS NOT missing THEN 'Not Significant' ELSE 'Significant'." In the >= part of the condition, NA values will evaluate to NA (not TRUE or FALSE) in a way that messes up the comparison you want to make.

x <- c(1, 0.01, NA)

# Is NOT missing
!is.na(x)
#> [1]  TRUE  TRUE FALSE

# Is greater than 0.05
x > 0.05
#> [1]  TRUE FALSE    NA ## Note result is NA here not FALSE

# "Is not significant" as 
# Is NOT missing AND is greater than 0.05
x
#> [1] 1.00 0.01   NA
!is.na(x) & x > 0.05  ## not what you want
#> [1]  TRUE FALSE FALSE

# "Is not significant" as 
# IS missing OR is greater than 0.05
x
#> [1] 1.00 0.01   NA
is.na(x) | x > 0.05
#> [1]  TRUE FALSE  TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM