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

setdiff in R: Set Difference of Vectors and Data Frames

How setdiff() works in R: vector and data-frame set difference with base, dplyr and data.table, duplicates, factors in R 4.5.0 and common errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In R, setdiff(x, y) returns the values that appear in x but not in y, with duplicates removed and the same mode as x. The order of the arguments matters: setdiff(x, y) and setdiff(y, x) give different answers. Base R’s setdiff() works on vectors; the dplyr and data.table packages provide versions (dplyr::setdiff(), data.table::fsetdiff()) that compare whole rows of data frames. This guide covers all three, with a worked research-data example, the R 4.5.0 change in how factors are handled, and the errors people most often meet. People also search for this as “setdiff r”; it is the same function.

What setdiff is used for in research

Set difference answers the question “which items are in this list but not in that one?” In research data work that question comes up constantly: which participant IDs are in the enrolment list but missing from the consent log, which sample identifiers appear in a freezer inventory but not in the sequencing manifest, which records were in last month’s export but have disappeared from this month’s, or which variables one dataset has that another lacks. Because the result is a set, it ignores how many times a value occurred and (in base R) the order in which values were listed, which is what you want for reconciliation checks between two identifier lists.

Set difference is one of a family of set operations documented together in R’s base documentation under “Set Operations”: union(x, y), intersect(x, y), setdiff(x, y), setequal(x, y) and is.element(el, set). The documentation states that the arguments should be vectors of the same mode and are meant to have no duplicated values. If you are new to vectors, see what a vector is in R first.

How to install or access it

Base R’s setdiff() ships with R itself, in the base package, so there is nothing to install: it is available in every R session. The documentation page is “Set Operations” in the R reference manual, also reachable from the console with ?setdiff.

The two data-frame versions come from packages published on CRAN. Install them from the R console with the standard installer and load them when needed:

install.packages("dplyr")
install.packages("data.table")
library(dplyr)
library(data.table)

Loading dplyr makes its setdiff() mask the base function for the rest of the session. The dplyr documentation notes that its versions are generic and that vector behaviour is kept through default methods that call the base functions, so existing vector code keeps working. data.table avoids the overlap by using a different name, fsetdiff().

Step-by-step: set difference of two vectors

1. Create the two vectors

Suppose enrolled lists participant IDs from the enrolment system and consented lists IDs found in the consent log. These IDs are illustrative values, not real study data.

enrolled  = c("P001", "P002", "P003", "P004", "P005")
consented = c("P002", "P004", "P005", "P006")

2. Take the difference in the direction you need

setdiff(enrolled, consented)
setdiff(consented, enrolled)

The first call returns "P001" "P003": enrolled participants with no consent record. The second returns "P006": a consent record with no enrolment. Both directions matter in a reconciliation, which is why running the function twice is the usual pattern.

3. Check your result with the documented identity

The base documentation includes an example that checks union(x, y) against the combination of setdiff(x, y), intersect(x, y) and setdiff(y, x). In other words, every value in either vector falls into exactly one of three groups: only in x, in both, or only in y. For the example above, those groups are "P001" "P003", "P002" "P004" "P005" and "P006".

4. Test membership instead when you only need TRUE or FALSE

The documentation states that is.element(x, y) is identical to x %in% y. If you want a logical vector the length of x rather than the unmatched values, use enrolled %in% consented; negating it with ! keeps the unmatched positions, which is useful when you need to filter a data frame by those positions.

Set difference of data frames

dplyr::setdiff()

The dplyr signature is setdiff(x, y, ...). It keeps the rows of x that are not in y. The two data frames must be compatible: the same column names (in any order) and compatible column types. The dots must be empty. The dplyr documentation gives this example:

df1 = tibble(x = 1:3)
df2 = tibble(x = 3:5)
setdiff(df1, df2)   # rows 1, 2
setdiff(df2, df1)   # rows 4, 5
symdiff(df1, df2)   # rows 1, 2, 4, 5

symdiff() returns rows that are in one data frame but not the other, so it is the two setdiff() calls combined. For the participant example, you would store IDs in a column such as id in each data frame and call setdiff(enrolled_df, consented_df). See select() in R to reduce each table to just the key columns first, because row-wise comparison uses every column: two rows that differ in any column count as different rows.

data.table::fsetdiff()

The data.table signature is fsetdiff(x, y, all = FALSE). It returns the rows of x not in y, like SQL’s EXCEPT or MINUS, as a data.table, and it retains row order. With all = FALSE (the default) duplicate rows are removed. With all = TRUE it keeps duplicates and returns max(0, xn - yn) copies of each row, where xn and yn are the number of times that row occurs in x and y. The data.table documentation’s own example uses x = c(1,2,2,2,3,4,4) and y = c(2,3,4,4,4,5). By that rule the default leaves the single row 1, while all = TRUE leaves 1 and two copies of 2, because 2 occurs three times in x and once in y. Complex and list columns are not supported by fsetdiff().

Output and how to read it

For vectors, the result is a vector with the same mode as x. A few properties follow from the documentation and are worth checking each time:

  • Duplicates are discarded. The first four functions in the family (union, intersect, setdiff and setequal) discard duplicated values in their arguments, so setdiff(c(1, 2, 2, 3), 3) returns 1 2, not 1 2 2. If you need to count how many times a value is unmatched, use fsetdiff(..., all = TRUE) on data tables, or tabulate separately.
  • Direction matters. An empty result from setdiff(enrolled, consented) says every enrolled ID has a consent record; it says nothing about consent records without enrolment. Check both directions.
  • An empty result has length zero. Use length(setdiff(x, y)) == 0 or setequal() when you want a single TRUE or FALSE for a script.
  • Row order is retained by fsetdiff(); the documentation does not promise a particular order for base vectors, so sort explicitly if order matters downstream.

R 4.5.0 and factors

The base documentation records a change at R 4.5.0. Before 4.5.0, operands were converted with as.vector(), so factors became character vectors. From R 4.5.0, same-kind vector-like operands keep their class, so the setdiff() of two factors returns a factor. The documentation also notes that union() and intersect() merge factor levels, and that levels such as “A” and “b” are different levels. If your analysis scripts must run on both old and new R, convert explicitly with as.character() before the call so the result type does not depend on the R version.

Troubleshooting

The result is not what I expected after loading dplyr

Loading dplyr masks the base function with a generic. For vectors, the dplyr documentation says the default methods call the base functions, so the result should match. For data frames, the comparison is row-wise across all columns, which is different from comparing one column. If you want only the IDs, extract the columns first: setdiff(df1$id, df2$id). If you need to be explicit about which function you are calling, write base::setdiff() or dplyr::setdiff().

Error about incompatible data frames

dplyr requires the same column names in both data frames (order does not matter) and compatible column types. Rename columns or convert types so both tables match before calling it, or drop to the key column and compare vectors.

Rows I expected to be removed are still present

Because the comparison covers all columns, a single differing column, such as a timestamp or a whitespace difference in a text field, makes two rows distinct. Reduce both tables to the identifying columns, or compare only the key column. The related guide on removing columns in R covers dropping the extra columns.

Duplicates disappeared

This is documented behaviour, not an error. Use fsetdiff(x, y, all = TRUE) if multiplicities matter, or count values with table() and compare the counts.

fsetdiff() fails on a column

The data.table documentation says complex and list columns are unsupported by fsetdiff() (only funion() supports them). Remove or convert those columns first.

Alternatives: base, dplyr and data.table

All three tools are open-source R packages or part of R itself. The table below maps the task you have to the function the documentation names for it. A separate data table below the article compares the three setdiff implementations.

Task Function Package
Values in x that are not in y setdiff(x, y) base R
Values in both intersect(x, y) base R
All distinct values from both union(x, y) base R
Test whether two sets have the same members setequal(x, y) base R
TRUE/FALSE membership for each element is.element(el, set) or %in% base R
Rows of one data frame that are not in another setdiff(x, y) dplyr
Rows in one data frame but not the other, either side symdiff(x, y) dplyr
Rows of x not in y, keeping duplicate counts fsetdiff(x, y, all = TRUE) data.table

Pairing set difference with a Venn diagram is a common way to present the overlap; see Venn diagrams in R.

Frequently asked questions

What does setdiff do in R?

setdiff(x, y) returns the distinct values in x that are not present in y. The result keeps the mode of x, and duplicates in the inputs are discarded.

Is setdiff(x, y) the same as setdiff(y, x)?

No. Set difference is asymmetric: setdiff(x, y) returns what is only in x, setdiff(y, x) returns what is only in y. For both at once on data frames, dplyr provides symdiff().

Does setdiff work on data frames?

Base setdiff() is designed for vectors. For data frames use dplyr::setdiff(), which keeps the rows of x not in y, or data.table::fsetdiff(), which does the same for data.tables.

How do I keep duplicates when taking a set difference?

Use fsetdiff(x, y, all = TRUE) from data.table, which returns max(0, xn – yn) copies of each row. Base and dplyr set operations remove duplicates.

Why does setdiff return a factor in newer R?

From R 4.5.0, same-kind vector-like operands keep their class, so setdiff() of two factors returns a factor. Earlier versions converted operands with as.vector(), so factors came back as character.

Sources

Data: Three R implementations of set difference: input, duplicate handling and result

Compares base R setdiff(), dplyr setdiff() and data.table fsetdiff() on what they accept, how they treat duplicates and what they return, compiled from each package's official reference documentation.

Period covered: 2026.

Three R implementations of set difference: input, duplicate handling and result
FunctionPackageInputDuplicate handlingResult
setdiff(x, y)base RVectors of the same modeDuplicated values discardedVector with the same mode/class as x (factors keep class from R 4.5.0)
setdiff(x, y, ...)dplyrData frames with the same column names and compatible typesDuplicates removed within x and yRows of x not in y
fsetdiff(x, y, all = FALSE)data.tabledata.tables (no complex or list columns)Duplicates removed when all = FALSERows of x not in y, row order retained
fsetdiff(x, y, all = TRUE)data.tabledata.tables (no complex or list columns)Duplicates kept: max(0, xn - yn) copiesRows of x not in y, row order retained

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 setdiff in R: Set Difference of Vectors and Data Frames

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 →