R filter_all() Function from dplyr

R filter_all() function from dplyr is used to subset rows from a data frame where all conditions are evaluated to TRUE. The specified conditions are similar to filter() but without comma separation.

This function is beneficial when you want to apply a uniform filter across every column in the dataset.

The condition is expressed using a predicate formula typically wrapped in all_vars() or any_vars().

Syntax

filter_all(.tbl, .vars_predicate, .preserve = FALSE)

Parameters

Name Description
.tbl It is an R object that can be a data frame or tibble.
.vars_predicate It is a quoted predicate expression returned by all_vars() or any_vars(). It can also be a function or formula. This function replicates this predicate across all columns.
.preserve It is a Logical argument suggesting whether to keep the original grouping structure.

Return value

It returns a filtered data frame or tibble where the rows meet the condition across all columns.

Example 1: Filtering where all columns satisfy a condition

Figure of R filter_all() Function from dplyr

library(dplyr)

df <- data.frame(col1 = c(1, 2, NA), col2 = c(NA, "b", "c"), col3 = c(4, 5, 6))

cat("Before using filter_all()", "\n")
print(df)

cat("After using filter_all()", "\n")
df %>% filter_all(all_vars(!is.na(.)))

Output

Output of dplyr filter_all() function

Example 2: Filtering numeric columns greater than a value

Filtering numeric columns greater than a value

Let’s filter rows where all column values are greater than a specific number.

library(dplyr)

df <- data.frame(col1 = c(1, 2, NA), col2 = c(NA, "b", "c"), col3 = c(4, 5, 6))

cat("Before using filter_all()", "\n")
print(df)

cat("After using filter_all()", "\n")
df %>% filter_all(all_vars(. > 1))

Output

Output of Filtering numeric columns greater than a value

That’s all!

Leave a Comment