I am aware of the all the question regarding the filter multiple conditions
with very comprehensive answers such as Q1, Q2, or even for removing NA values
Q3, Q4.
But I have a different question, How I can do filter
using dplyr
or even data.table
functions to keep both NA
values and a conditional parameters
?
as an example in the following I'd like to keep all of the values in Var3
which is >5
PLUS NA
values
.
library(data.table)
library(dplyr)
Var1<- seq(1:5)
Var2<- c("s", "a", "d", NA, NA)
Var3<- c(NA, NA, 2, 5, 2)
Var4<- c(NA, 5, 1, 3,4)
DT <- data.table(Var1,Var2,Var3, Var4)
DT
Var1 Var2 Var3 Var4
1: 1 s NA NA
2: 2 a NA 5
3: 3 d 2 1
4: 4 NA 5 3
5: 5 NA 2 4
The Expected results:
Var1 Var2 Var3 Var4
1: 1 s NA NA
2: 2 a NA 5
3: 3 d 2 1
4: 5 NA 2 4
I have tried followings but not successful:
##Using dplyr::filter
DT %>% filter(!Var3 ==5)
Var1 Var2 Var3 Var4
1 3 d 2 1
2 5 <NA> 2 4
# or
DT %>% filter(Var3 <5 & is.na(Var3))
[1] Var1 Var2 Var3 Var4
<0 rows> (or 0-length row.names)
## using data.table
DT[DT[,.I[Var3 <5], Var1]$V1]
Var1 Var2 Var3 Var4
1: NA NA NA NA
2: NA NA NA NA
3: 3 d 2 1
4: 5 NA 2 4
Any help with explanation is highly appreciated!