R all_vars() Function from dplyr

The dplyr::all_vars() function in R is a helper function that applies a condition across all selected columns and returns TRUE if the condition is met for every element in each column.

This function is typically used in row-wise filtering operations, where you want to check if a condition holds true for every element across a set of columns.

This function is often used in combination with functions like filter_all(), filter_if(), or filter_at().

Syntax

all_vars(.predicate)

Parameters

Name Description
.predicate It is a logical condition to be applied across the selected columns. This condition is usually written in a formula style with ~.

Return value

It returns a filtered data frame or tibble.

Example 1: Filtering with all_vars()

Understanding of R all_vars() Function from dplyr

library(dplyr)

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

df %>% filter_all(all_vars(. > 2))

Output

   col1   col2   col3
1    3     6      9

We filtered rows where all specified columns meet the condition.

Example 2: Usage with filter_if()

Using all_vars() with filter_if()

library(dplyr)

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)


df %>% filter_if(is.numeric, all_vars(. > 1))

Output

  col1  col2   col3
1  2     5      8
2  3     6      9

Example 3: Usage with filter_at()

Using all_vars() with filter_at()

library(dplyr)

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

df %>% filter_at(vars(starts_with("col")), all_vars(. > 2))

Output

  col1  col2  col3
1  3     6     9

We filtered rows based on a condition that applies to a subset of columns.

Leave a Comment