Skip to main content
v2026.11,986 entries · CC-BY 4.0

Filter Function in R: dplyr filter(), Filter() and stats::filter()

How the filter function in R works: dplyr filter() for rows, base Filter() for vectors, stats::filter() for time series, with NA behaviour.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

The filter function in R usually means dplyr’s filter(), which keeps the rows of a data frame for which every logical condition you give it is TRUE, for example filter(starwars, species == "Human"). The name is shared by two other functions, base R’s Filter() for vectors and lists and stats::filter() for time-series smoothing, and they do unrelated jobs, so check which one your code is calling before you debug it.

What it is used for in research

In an analysis workflow, filter() is the step that defines your analytic sample: keep the participants with complete consent records, the observations inside a study window, the samples that passed quality control. It returns a subset of rows in their original order, with the columns unchanged. The dplyr reference describes the output as the same type as the input, so a tibble in gives a tibble out, and the rows are always a subset rather than a re-ordered copy.

Because the inclusion rules live in code, a reader can see exactly which rows were excluded and why. That matters for reproducibility, and it pairs naturally with the pipe: see the pipe operator in R for how |> chains a filter into the steps before and after it. The wider package is covered in the dplyr package in R.

The three functions called filter

  • dplyr::filter() keeps rows of a data frame that satisfy logical expressions. This is the function almost every search for the filter function in R is after.
  • base Filter() (capital F, in the base package) keeps the elements of a vector or list for which a one-argument predicate function returns TRUE.
  • stats::filter() applies a linear filter to a time series, either a moving-average style convolution or a recursive (autoregressive) filter. It does not select rows at all.

When both dplyr and stats are in play, the call filter(x, ...) resolves to whichever package was attached last, so writing dplyr::filter() or stats::filter() explicitly removes the ambiguity.

How to install or access it

dplyr is a package, not part of base R. The dplyr project site gives two ways to install it: the whole tidyverse, or dplyr alone.

install.packages("tidyverse")
# or, to install only dplyr:
install.packages("dplyr")

Load it in each session with library(dplyr). The project site also lists a development version installed with pak::pak("tidyverse/dplyr"). Base Filter() and stats::filter() ship with R itself and need no installation. The reference page used here is labelled dplyr 1.2.1; the dplyr site’s documentation is the place to confirm the signature in the version you have installed.

Step-by-step: filter rows with dplyr::filter()

The signature in the reference is filter(.data, ..., .by = NULL, .preserve = FALSE). The examples below use the starwars data set that ships with dplyr, and the row counts are the ones printed in the dplyr reference.

  1. Load the package. Run library(dplyr).
  2. Keep rows that meet one condition. filter(starwars, species == "Human") keeps 35 rows.
  3. Combine conditions with a comma or &. Multiple expressions in ... are combined with &, and only rows where all of them are TRUE are kept. filter(starwars, hair_color == "none" & eye_color == "black") keeps 9 rows.
  4. Use OR with when_any() or |. The reference says to wrap expressions in when_any() for OR logic, and its examples also write the OR with |: filter(starwars, hair_color == "none" | eye_color == "black") keeps 39 rows.
  5. Pipe it. starwars |> filter(species == "Human") gives the same result as step 2.
  6. Filter within groups. Add .by for a per-operation grouping, described in the reference as an alternative to group_by().

Filtering within groups with .by

Filtering expressions are evaluated within each group, so functions that aggregate, lag or rank can give different answers on grouped data. The dplyr reference shows this with a comparison against the mean. starwars |> filter(mass > mean(mass, na.rm = TRUE)) compares each character to the overall mean mass and keeps 10 rows. starwars |> filter(mass > mean(mass, na.rm = TRUE), .by = gender) compares each character to the mean for their own gender and keeps 15 rows. If the data are already grouped with group_by(), the .preserve argument matters: with the default FALSE the grouping structure is recalculated from the result, and with TRUE the original grouping is kept.

Dropping rows with filter_out()

The same reference page documents filter_out(), which takes the same arguments but drops the rows for which all expressions are TRUE instead of keeping them. filter_out(starwars, hair_color == "none") returns 49 rows. If your installed dplyr does not have filter_out(), update the package or write the negated condition with filter(), and read the next section on missing values before you do. For the other ways of removing rows, including slicing by position, see removing rows in R.

Filter() on vectors and lists

Base R’s Filter(f, x) takes a unary predicate f and a vector x, and returns the subset of x for which the predicate gives TRUE. The R documentation notes that NA from the predicate is currently always taken as FALSE. Its example keeps the functions among the objects of the base environment: Filter(is.function, sapply(ls(baseenv()), get, baseenv())), and the complement uses Negate(is.function) as the predicate. Filter() belongs to the same functional-programming family as Map() and Reduce(); for the apply family see the apply function in R.

stats::filter() for time series

The signature is filter(x, filter, method = c("convolution", "recursive"), sides = 2, circular = FALSE, init). With method = "convolution" it computes a moving average with the weights you supply in the second argument; with "recursive" it computes an autoregression. The sides argument sets whether the filter uses only past values (sides = 1) or is centred (sides = 2). By default the ends of the series come back as NA; circular = TRUE wraps the series around instead. init applies to recursive filters only. NA values are allowed in x but not in the filter coefficients, and the recursive filter is not checked for invertibility. The documentation’s examples include filter(x <- 1:100, rep(1, 3)) and filter(presidents, rep(1, 3)). The result is a time-series object.

Output and how to read it

A dplyr filter returns a data frame or tibble of the same class as its input. Check the row count: a tibble prints its dimensions, and nrow() gives the number directly. Compare it with the count before filtering and with what you expected. If you filter a data set in several steps, record the count after each step so your methods section can report how many rows each exclusion rule removed.

The table below shows the row counts printed in the dplyr reference for two grouping choices and for the missing-value cases discussed in the troubleshooting section.

Call (starwars) Rows kept
filter(species == "Human") 35
filter(mass > mean(mass, na.rm = TRUE)) 10
filter(mass > mean(mass, na.rm = TRUE), .by = gender) 15
filter(hair_color != "blond") 79
filter(hair_color != "blond" | is.na(hair_color)) 84
filter_out(hair_color == "blond") 84

Troubleshooting

Rows with missing values disappear

Both filter() and filter_out() treat NA like FALSE. That means filter() drops rows where the condition is NA, and filter_out() keeps them. In the dplyr example, filter(hair_color != "blond") returns 79 rows because rows with a missing hair colour are dropped, while filter_out(hair_color == "blond") returns 84. Adding | is.na(hair_color) to the filter() version also gives 84. The reference states that together filter() and filter_out() capture every row exactly once, and that needing !=, ! or explicit is.na() handling is a sign the other function may be simpler. Base subsetting behaves differently: with [, an NA in the logical index returns a fully missing row, as described on the same page. See subsetting in R for the base methods.

The wrong filter runs, or stats::filter is masked

If a time-series call fails after you load dplyr, or a dplyr call fails after you load a package that exports its own filter, name the package: dplyr::filter(...) or stats::filter(...). This is the reliable fix whichever package was attached last.

An error about an object not found, or a result that ignores your condition

Expressions in ... are written in terms of the columns of .data, so column names go unquoted and the comparison uses ==, not =. Values you compare against, such as strings, need quotes.

Aggregates give different answers once data are grouped

Because expressions are evaluated per group, mean(), lag() or ranking calls inside filter() change meaning on grouped input. Use .by deliberately, or ungroup() first, and compare the row counts as in the 10 versus 15 example above.

Free alternatives

All of the options below are part of R itself, and each performs a different version of the job.

Option What it does Note on missing values
filter_out() in dplyr Drops rows for which all expressions are TRUE NA treated like FALSE, so those rows are kept
Base subset() and [ ] Row selection without dplyr Per the dplyr reference, [ returns a fully missing row for NA in the index
Base Filter() Keeps vector or list elements where a predicate is TRUE NA from the predicate taken as FALSE

Frequently asked questions

What does the filter function do in R?

In dplyr, filter() keeps the rows of a data frame for which all of your logical expressions are TRUE and returns them in their original order with all columns intact.

How do I filter on more than one condition?

List the conditions separated by commas or join them with &; all must be TRUE for a row to be kept. For OR logic, wrap the expressions in when_any() or use | as in the dplyr reference examples.

Why did filter() remove my rows with NA?

dplyr treats NA like FALSE, so a row where the condition is NA is dropped by filter(). Use filter_out() to drop rows by a condition while keeping the NA rows, or add is.na() to the condition.

What is the difference between filter() and Filter()?

dplyr’s filter() selects rows of a data frame using logical expressions. Base Filter() takes a predicate function and a vector or list, and returns the elements for which the predicate is TRUE.

Is stats::filter() the same as dplyr::filter()?

No. stats::filter() applies a convolution or recursive linear filter to a time series. Call each one with its package prefix when both are loaded.

Sources

  • dplyr reference: Keep or drop rows that match a condition, https://dplyr.tidyverse.org/reference/filter.html (read 2026-11-14)
  • dplyr project site, installation, https://dplyr.tidyverse.org/ (read 2026-11-14)
  • R documentation, funprog (Filter, Map, Reduce), https://stat.ethz.ch/R-manual/R-devel/library/base/html/funprog.html (read 2026-11-14)
  • R documentation, stats::filter (linear filtering on a time series), https://stat.ethz.ch/R-manual/R-devel/library/stats/html/filter.html (read 2026-11-14)

Data: The three R functions named filter: input, NA handling and output

Compares dplyr::filter(), dplyr::filter_out(), base Filter(), base [ indexing and stats::filter() on what they take as input, how they treat NA, and what they return. Compiled from the dplyr reference page and the R manual pages for funprog and stats::filter.

The three R functions named filter: input, NA handling and output
FunctionPackageInputTreatment of NAReturns
filter()dplyrData frame with logical expressionsCondition NA treated like FALSE: row droppedRows kept, original order, same type as input
filter_out()dplyrData frame with logical expressionsCondition NA treated like FALSE: row keptRows not matching, original order, same type as input
Filter()baseUnary predicate and a vectorNA from predicate always taken as FALSESubset of the vector where predicate is TRUE
[ with a logical indexbaseVector or data frame with logical indexNA index gives a fully missing rowSelected rows including NA rows
filter() with method convolution or recursivestatsNumeric series and filter coefficientsNA allowed in x, not in the filter coefficientsTime-series object, NA at ends unless circular = TRUE

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Filter Function in R: dplyr filter(), Filter() and stats::filter()

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →