0

[Data set]

X Y Z
4.98 NA NA
5.28 NA 3.21
5.12 5.14 3.16
5.09 5.12 3.18
0 0 7.12
0 0 NA
d %>% filter(x==0 | y==0 | z==0 | is.na(x) | is.na(y) | is.na(z))

Above R code give me correct results where it filers the dataset and display everything with either 0 or NA in any of the x, y or z as below

X Y Z
4.98 NA NA
5.28 NA 3.21
0 0 7.12
0 0 NA

But when I reverse the condition to negations it is showing everything.

d %>% filter(x!=0 | y!=0 | z!=0 | !is.na(x) | !is.na(y) | !is.na(z))

The expected result is

X Y Z
5.12 5.14 3.16
5.09 5.12 3.18

But I received the entire data set

Could you please let me know what mistake I made ?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

2 Answers2

0

I think this may be a logic issue rather than an R issue here. If you replace your or statements with and then I think you will obtain the intended result and the negation of your original statement. In other words, d %>% filter(x!=0 & y!=0 & z!=0 & !is.na(x) & !is.na(y) & !is.na(z)).

Carey Caginalp
  • 432
  • 2
  • 5
0

To reverse the condition you can add ! to your original condition.

library(dplyr)

d %>% filter(!(x==0 | y==0 | z==0 | is.na(x) | is.na(y) | is.na(z)))

#     x    y    z
#1 5.12 5.14 3.16
#2 5.09 5.12 3.18

data

d <- structure(list(x = c(4.98, 5.28, 5.12, 5.09, 0, 0), y = c(NA, 
NA, 5.14, 5.12, 0, 0), z = c(NA, 3.21, 3.16, 3.18, 7.12, NA)), row.names = c(NA, 
-6L), class = "data.frame")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213