R filter_at() Function from dplyr

The dplyr::filter_at() function allows you to apply filtering conditions to a set of columns in a data frame or tibble.

It applies a predicate expression to a selection of variables in a data frame or tibble.

The selection of variables is specified using a list of columns or a selection helper like vars().

Syntax

filter_at(.tbl, .vars, .vars_predicate, .preserve = FALSE)

Parameters

Name Description
.tbl It is a data frame or tibble
.vars It is a list of columns generated by vars().
.vars_predicate It is a quoted predicate expression as returned by all_vars() or any_vars().
.preserve It is a logical argument suggesting whether to keep or recalculate the original grouping structure. The default value is FALSE.

Return value

It returns a filtered data frame or tibble.

Example: Basic usage

Basic understanding of R filter_at() 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_at(vars(starts_with("col")), all_vars(. > 2))

Output

  col1  col2   col3
1   3     6     9

We applied a filter to columns starting with “col” and returned the rows whose values are > 2.

While filter_at() offers flexibility in applying conditions to specified columns, the more recent versions of dplyr encourage the use of the filter() with across() for such operations, offering a more consistent and flexible syntax.

Leave a Comment