Unable to multiply (filter) data frame due to NA

Why filterdoesn't dplyr return the same data.frame in the code below as a subset of the R base?

In fact, none of them work as expected. I would like to remove observations / rows that are at the same time b==1 AND c==1. That is, I would like to delete only the third line.

require(dplyr)
df <- data.frame(a=c(0,0,0,0,1,1,1), b=c(0,0,1,1,0,0,1), c=c(1,NA,1,NA,1,NA,NA))

filter(df, !(b==1 & c==1))

df[!(df$b==1 & df$c==1),]
+4
source share
4 answers

Or use complete.casesto convert NAto FALSEin a logical vector of the result so that you can select the appropriate rows after the negation, and this takes advantage of the fact that NA & F = F:

filter(df, !(b == 1 & c == 1 & complete.cases(df[c('b', 'c')])))

#   a b  c
# 1 0 0  1
# 2 0 0 NA
# 3 0 1 NA
# 4 1 0  1
# 5 1 0 NA
# 6 1 1 NA

NA, , :

NA & F
# [1] FALSE
NA | T
# [1] TRUE
NA & T
# [1] NA
NA | F
# [1] NA
+3

, :

filter(df, !((b==1 & c==1) %in% TRUE))
#  a b  c
#1 0 0  1
#2 0 0 NA
#3 0 1 NA
#4 1 0  1
#5 1 0 NA
#6 1 1 NA

# or equivalently in data.table
dt[!((b==1 & c==1) %in% TRUE)]

, , / !(b==1 & c==1) | is.na(b+c) .

+3

data.table

library(data.table)
setDT(df)[df[,!(b==1 & c== 1& complete.cases(.SD[, c('b', 'c'), with = FALSE]))]]
#   a b  c
#1: 0 0  1
#2: 0 0 NA
#3: 0 1 NA
#4: 1 0  1
#5: 1 0 NA
#6: 1 1 NA
+2

, NA . 4 :

1: 2-

n <- (df$b+df$c==2)
df[n %in% c(NA, "FALSE"),]
  a b  c
1 0 0  1
2 0 0 NA
4 0 1 NA
5 1 0  1
6 1 0 NA
7 1 1 NA

2:

df[!(complete.cases(df$b,df$c) & df$b+df$c == 2),]
  a b  c
1 0 0  1
2 0 0 NA
4 0 1 NA
5 1 0  1
6 1 0 NA
7 1 1 NA

3: Loop/Function

filterwithNA <- function(df,n){
  for(i in 1:nrow(df)){
    if(!is.na(df$b[i]) & !(is.na(df$c[i]))){
      if(df$b[i] == n & df$c[i] == n){
        df <- df[-i,]
      }
    }
  }
  return(df)
}

filterwithNA(df, n=1)
  a b  c
1 0 0  1
2 0 0 NA
4 0 1 NA
5 1 0  1
6 1 0 NA
7 1 1 NA

4:

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

df[!(df$b==1 & df$c==1),]
df[df==999] <- NA
df
  a b  c
1 0 0  1
2 0 0 NA
4 0 1 NA
5 1 0  1
6 1 0 NA
7 1 1 NA
+1

Source: https://habr.com/ru/post/1651237/


All Articles