EML
EML

Reputation: 671

Ifelse with NA values in columns

I am trying to apply an ifelse statement on columns that have NA and would like the else condition to be given when NA is present. Instead, I just get NA. My actual case uses multiple columns making it difficult for me to find a solution (e.g., I can't convert NA's to 0 because there are some cases that are missing across all columns).

Data:

df <- data.frame(a=c(NA, 1:3, NA) , b=c(NA,4:6,NA), c=c(5,10,15,20,25))

   a  b  c 
1 NA NA  5    
2  1  4 10     
3  2  5 15     
4  3  6 20     
5 NA NA 25     

Attempt:

df2 <- df %>% mutate(check=ifelse((a<=2&b>4)|c==25,1,0))

Result:

   a  b  c check
1 NA NA  5    NA
2  1  4 10     0
3  2  5 15     1
4  3  6 20     0
5 NA NA 25     1

Desired output:

   a  b  c check
1 NA NA  5   **0**
2  1  4 10     0
3  2  5 15     1
4  3  6 20     0
5 NA NA 25     1

Upvotes: 2

Views: 844

Answers (3)

Mike V
Mike V

Reputation: 1354

My answer is not exactly what you want, but if you want to replace NA values, you can try this one

df[is.na(df)] <- 0

Output

  a b  c
1 0 0  5
2 1 4 10
3 2 5 15
4 3 6 20
5 0 0 25

Upvotes: 1

r.user.05apr
r.user.05apr

Reputation: 5456

You can deal with the na's in a separate line:

df2 <- df %>% 
  #mutate_at(vars("a", "b", "c"), ~if_else(is.na(.x), 0.0, as.double(.x))) %>% # double?
  mutate_at(vars("a", "b", "c"), ~if_else(is.na(.x), 0L, as.integer(.x))) %>% # or integer
  mutate(check=ifelse((a<=2&b>4)|c==25,1,0))

Upvotes: 2

Alexis
Alexis

Reputation: 2294

Let's combine previous comment into the script:

library(dplyr)
df <- data.frame(a=c(NA, 1:3, NA) , b=c(NA,4:6,NA), c=c(5,10,15,20,25))
df2 <- df %>% mutate(check=ifelse((a<=2&b>4)|c==25,1,0))
# if dataset 2 contains NA, transform into 0
df2$check[is.na(df2$check)] <- 0

Upvotes: 1

Related Questions