Home > Back-end >  How to drop rows by condition in R?
How to drop rows by condition in R?

Time:08-09

From this dataframe I need to drop all the rows which have TRUEs in every column. However, since I need to automatize the process I cant drop them with column names or column indexes. I need something else

df1  <- c(TRUE,TRUE,FALSE,TRUE,TRUE)
df2 <- c(TRUE,FALSE,FALSE,TRUE,TRUE)
df3 <- c(FALSE,TRUE,TRUE,TRUE,TRUE)

df <- data.frame(df1,df2,df3)

    df1   df2   df3
1  TRUE  TRUE FALSE
2  TRUE FALSE  TRUE
3 FALSE FALSE  TRUE
4  TRUE  TRUE  TRUE
5  TRUE  TRUE  TRUE

CodePudding user response:

This should be the fastest solution:

df[!do.call(pmin, df), ]
#     df1   df2   df3
# 1  TRUE  TRUE FALSE
# 2  TRUE FALSE  TRUE
# 3 FALSE FALSE  TRUE

CodePudding user response:

Instead of row-wise operations, a straightforward way is:

df[rowSums(df) < ncol(df), ]
#    df1   df2   df3
#1  TRUE  TRUE FALSE
#2  TRUE FALSE  TRUE
#3 FALSE FALSE  TRUE

CodePudding user response:

base R:

df[!apply(df, 1, all), ]
#    df1   df2   df3
#1  TRUE  TRUE FALSE
#2  TRUE FALSE  TRUE
#3 FALSE FALSE  TRUE

tidyverse:

library(dplyr)
filter(df, !if_all())
#    df1   df2   df3
#1  TRUE  TRUE FALSE
#2  TRUE FALSE  TRUE
#3 FALSE FALSE  TRUE

CodePudding user response:

  • We can use rowwise function from dplyr library
library(dplyr)

df |> rowwise() |> filter(!all(c_across() == TRUE))
  • output
# A tibble: 3 × 3
# Rowwise: 
  df1   df2   df3  
  <lgl> <lgl> <lgl>
1 TRUE  TRUE  FALSE
2 TRUE  FALSE TRUE 
3 FALSE FALSE TRUE 
  • Related