RL_Pug
RL_Pug

Reputation: 867

How to filter data with dplyr to retrieve NAs along with another value together?

I have a dataset that looks like this

X      Y      
121    Yes
122    No
123    NA
124    Yes
125    NA

How can I filter out the "Yes" values from column Y ? I only want 'No' and 'NA'

My Desired output is this

X      Y      
122    No
123    NA
125    NA

I've tried

data2 <- data %>% filter(Y != "Yes") #But I lose my NAs with this command.

& 

data2 <- data %>% filter(Y %in% c(is.na(Y), "No")  #Doesn't work

What am i doing wrong?

Upvotes: 0

Views: 39

Answers (2)

akrun
akrun

Reputation: 887078

We can use subset from base R

subset(data, Y == "No"|is.na(Y))

data

data <- structure(list(X = 121:125, Y = c("Yes", "No", NA, "Yes", NA)), 
    class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 0

vanao veneri
vanao veneri

Reputation: 1054

data2 <- data %>% filter(is.na(Y) | Y == "No")  

The line means "or". Your mistake was that is.na(Y) returns either TRUE or FALSE and those values are not in your data.

Upvotes: 2

Related Questions