dplyr count() and distinct() in R: Practical Examples
Learn how to use dplyr count() and distinct() in R, from counting a few rows and finding unique values to grouped counts, duplicate checks, percentages, and advanced data-cleaning workflows.
What do count() and distinct() do in R?
count() and distinct() are useful dplyr functions for counting rows and finding unique values in R. They often appear early in data exploration because they help you understand what is in a dataset before you perform more detailed analysis.
Use count() when you want to know how often each category or combination occurs. Use distinct() when you want to see the unique values or combinations themselves. For example, count how many orders came from each region, or find the list of customers who appear in an order table.
| Function | Main purpose | Example question |
|---|---|---|
count() | Counts rows by value or combination | How many orders came from each region? |
distinct() | Returns unique values or combinations | Which regions appear in the data? |
n_distinct() | Counts the number of unique values | How many different customers placed orders? |
These functions work well with the pipe operator and other dplyr verbs. If you are new to data manipulation, first review the dplyr tutorial, or learn how to group and summarise records in group_by() and summarise().
Create sample data for the examples
We will use a small sales dataset. Each row represents one transaction and includes its region, product, customer ID and sales amount. Some customers appear more than once, which gives us realistic examples for counting and finding unique records.
library(dplyr)
sales_data <- tibble(
region = c("East", "West", "East", "West", "East",
"South", "South", "East", "West", "South"),
product = c("Laptop", "Laptop", "Phone", "Phone", "Laptop",
"Phone", "Laptop", "Phone", "Laptop", "Phone"),
customer = c("C101", "C102", "C101", "C103", "C104",
"C105", "C102", "C106", "C102", "C105"),
sales = c(1200, 1500, 800, 950, 900, 700, 1100, 650, 1800, 850)
)
sales_data
| region | product | customer | sales |
|---|---|---|---|
| East | Laptop | C101 | 1200 |
| West | Laptop | C102 | 1500 |
| East | Phone | C101 | 800 |
| West | Phone | C103 | 950 |
| East | Laptop | C104 | 900 |
| South | Phone | C105 | 700 |
| South | Laptop | C102 | 1100 |
| East | Phone | C106 | 650 |
| West | Laptop | C102 | 1800 |
| South | Phone | C105 | 850 |
Notice that customer C101, C102 and C105 appear multiple times. That is not necessarily an error: a customer can make multiple purchases. Whether repeated rows are duplicates depends on what one row is supposed to represent.
1. Your first count() example
The simplest way to count observations by category is to provide the column name to count(). To count how many transactions belong to each region, write:
sales_data |>
count(region)
| region | n |
|---|---|
| East | 4 |
| West | 3 |
| South | 3 |
The output contains one row for each region and a count column called n. East has four transactions, while West and South each have three. You do not need to write group_by() and summarise(n = n()) for this common task because count() provides a shorter way to do it.
Count a different column
Count transactions by product instead:
sales_data |>
count(product)
| product | n |
|---|---|
| Laptop | 5 |
| Phone | 5 |
Use the column that answers your question. Counting product tells you how many transaction rows involve each product; it does not necessarily tell you how many individual units were sold. For units, you would sum a units column rather than count rows.
2. Sort counts and rename the count column
When there are many categories, sorting the result makes the most common values easier to spot. Set sort = TRUE to sort by frequency, from largest to smallest:
sales_data |>
count(product, sort = TRUE)
You can also rename the frequency column using name. This is useful when a more descriptive column name makes a report easier to read:
sales_data |>
count(region, name = "transactions")
The result now uses transactions rather than the default n. A clear name is particularly helpful when you join the count result to another table or use it in a chart.
Sort explicitly with arrange()
The equivalent explicit approach is to count first and then sort the resulting count column:
sales_data |>
count(region) |>
arrange(desc(n))
This is handy when you want to apply additional sorting logic or sort by another summary column. See the dplyr arrange() tutorial for more sorting examples.
3. Count by multiple columns in dplyr
To count rows for each combination of two or more columns, pass the columns to count(). For example, count transactions by both region and product:
sales_data |>
count(region, product)
| region | product | n |
|---|---|---|
| East | Laptop | 2 |
| West | Laptop | 2 |
| East | Phone | 2 |
| West | Phone | 1 |
| South | Phone | 2 |
| South | Laptop | 1 |
Each row in the output represents a distinct region-product combination. East-Laptop and East-Phone are separate groups, as are West-Laptop and West-Phone. This is useful for cross-tabulation, sales reporting, survey analysis and checking the distribution of categories.
Count by three columns
The same pattern works with three or more variables. Imagine an orders table with region, product and payment_method:
orders |>
count(region, product, payment_method, sort = TRUE)
R returns one row per observed combination and counts how often it occurs. If a combination is not present in the original data, it will not normally appear as a row in this result. If you need every possible combination, including zero-count combinations, you can build a complete set of combinations and join the observed counts to it.
4. Filter before and after counting
You can combine count() with filter(). Filtering before counting limits the source rows; filtering after counting limits the summary rows.
Filter the data before counting
For example, count products only in the East region:
sales_data |>
filter(region == "East") |>
count(product)
Only East transactions are passed to count(), so the result describes product frequency in that region alone.
Filter the count results
To show only categories with at least three transactions, count first and filter the count column:
sales_data |>
count(product) |>
filter(n >= 3)
This pattern is useful for finding common categories, frequent events or high-volume customers. Be clear about the difference: filtering raw data and filtering summary results answer different questions.
5. Calculate counts and percentages
Counts are often easier to interpret when you also know what proportion of the total they represent. After counting rows, use mutate() to calculate a percentage:
sales_data |>
count(region) |>
mutate(percent = 100 * n / sum(n))
Here, sum(n) is the total number of transactions across the counted regions. The percent column gives each region's share of all transactions. You can round the result for display:
sales_data |>
count(region) |>
mutate(percent = round(100 * n / sum(n), 1))
Calculate percentages within a group
For a more advanced example, calculate each product's share of transactions within its region. First count each region-product combination, then group the counts by region before calculating percentages:
sales_data |>
count(region, product) |>
group_by(region) |>
mutate(percent_within_region = 100 * n / sum(n)) |>
ungroup()
The percentages within each region sum to approximately 100, allowing for rounding. This is useful for comparing product mix across locations even when the regions have different numbers of transactions.
6. Your first distinct() example
Use distinct() to return unique values from a column. For example, to find which regions occur in the dataset:
sales_data |>
distinct(region)
| region |
|---|
| East |
| West |
| South |
Each region appears once in the result, even if the original data contains many transactions from that region. This is a quick way to inspect the categories present in a dataset.
Find unique products
sales_data |>
distinct(product)
This returns the distinct product names. The result is not a frequency table: it does not tell you how many times each product appears. Use count(product) when you need frequencies.
7. Find unique combinations of columns
Pass more than one column to distinct() to return unique combinations. For example, list the region-product pairs that occur in the sales data:
sales_data |>
distinct(region, product)
| region | product |
|---|---|
| East | Laptop |
| West | Laptop |
| East | Phone |
| West | Phone |
| South | Phone |
| South | Laptop |
A combination is retained once, even if several transactions share the same region and product. This is useful for checking category combinations, creating lookup tables, or seeing which pairings exist before building a report.
Keep only unique customer IDs
sales_data |>
distinct(customer)
This produces one row for each customer ID in the data. It is useful for generating a list of customer identifiers, but it does not mean the full transaction records have been deduplicated.
8. Keep other columns with .keep_all = TRUE
By default, distinct() returns only the columns used to identify unique rows. If you want to keep the remaining columns while selecting the first row for each distinct key, use .keep_all = TRUE:
sales_data |>
distinct(customer, .keep_all = TRUE)
The result keeps the first transaction for each customer in the current row order, along with its region, product and sales value. This is not automatically the best transaction to retain; it is simply the first one encountered.
Important: If the retained row matters, arrange the data before using distinct(). For example, sort by date first if you want the earliest record, or sort by descending sales if you want the highest-value transaction per customer.
Keep the highest-value transaction per customer
sales_data |>
arrange(desc(sales)) |>
distinct(customer, .keep_all = TRUE)
Because the rows are sorted from highest to lowest sales first, the first row encountered for each customer has that customer's highest transaction value. In a real dataset, include a reliable date or tie-breaker if multiple records share the same value.
9. Find and remove duplicate rows
Duplicate handling begins with a key question: what makes two records duplicates? Two rows can have the same customer ID but represent separate valid purchases. Conversely, two identical rows may be accidental copies. Choose the columns that define a duplicate according to the meaning of the data.
Remove identical complete rows
clean_data <- sales_data |>
distinct()
With no columns specified, distinct() keeps unique complete rows. Rows are considered duplicates when their values match across all columns.
Identify repeated customer IDs
To inspect how often each customer appears, use count():
sales_data |>
count(customer, sort = TRUE)
To keep only customers with more than one transaction, filter the counts:
sales_data |>
count(customer) |>
filter(n > 1)
This finds customers with multiple records, not necessarily duplicate transactions. It is often a useful data-quality check, but repeated IDs are expected in transaction-level data.
Find duplicate combinations of columns
Suppose a dataset should contain one record per combination of customer and product. You can check how many times each pair occurs:
sales_data |>
count(customer, product) |>
filter(n > 1)
Use this only if that pair is meant to be unique for your data. If customers can buy the same product multiple times, repeated pairs may be legitimate.
10. Count unique values with n_distinct()
Sometimes you do not need a list of unique values; you only need the number of unique values. The dplyr function n_distinct() returns that number directly.
sales_data |>
summarise(unique_customers = n_distinct(customer))
This calculates how many different customer IDs appear in the data, regardless of how many transactions each customer made.
Count unique customers by region
Combine group_by() and summarise() to count distinct customers separately for each region:
sales_data |>
group_by(region) |>
summarise(
unique_customers = n_distinct(customer),
transactions = n(),
.groups = "drop"
)
This is different from counting transactions. A customer who makes several purchases in the same region contributes several rows to transactions, but only one to unique_customers for that region.
n_distinct() compared with distinct()
| Goal | Function | Example |
|---|---|---|
| Return the unique customer IDs | distinct() | distinct(sales_data, customer) |
| Count the unique customer IDs | n_distinct() | n_distinct(sales_data$customer) |
| Count rows for each customer | count() | count(sales_data, customer) |
11. Advanced count() and distinct() examples
Count unique customers by product
To see how many different customers purchased each product, use n_distinct() within a grouped summary:
sales_data |>
group_by(product) |>
summarise(
unique_customers = n_distinct(customer),
transaction_count = n(),
total_sales = sum(sales),
.groups = "drop"
)
This combines three measures: distinct customers, number of transaction rows and total sales. They answer different business questions, so avoid treating them as interchangeable.
Count combinations, then keep only frequent ones
For a large dataset, you may want to find region-product combinations with at least five records:
orders |>
count(region, product, sort = TRUE) |>
filter(n >= 5)
Replace orders and the column names with those in your own data. This workflow can reveal common combinations, while rare combinations may warrant further inspection depending on the analysis.
Use count() with a pipeline
Here is a complete pattern that filters to one region, counts products, calculates their percentage of transactions in that region and sorts the result:
sales_data |>
filter(region == "East") |>
count(product) |>
mutate(percent = round(100 * n / sum(n), 1)) |>
arrange(desc(n))
Each step has a distinct job: filter the source rows, count the remaining categories, calculate percentages from those counts, and sort the summary for presentation.
Use distinct() before a join
Lookup tables are often expected to have one row per key. Before joining a customer table to another table, inspect whether its key is unique:
customers |>
count(customer_id) |>
filter(n > 1)
If the query returns any rows, the key is repeated. Do not automatically remove these records: investigate why they repeat and decide which record is correct. Duplicate keys in a lookup table can multiply rows during a join and change totals.
Count missing values
Missing values can be treated as a category in a frequency check. For example:
sales_data |>
mutate(region = tidyr::replace_na(region, "Missing")) |>
count(region)
This example uses replace_na() from tidyr to label missing region values before counting. Only use a label such as "Missing" if it cannot be confused with a genuine category. Another option is to count missing values directly with sum(is.na(region)) or use count(is.na(region)) to compare missing and non-missing records.
12. dplyr count() and distinct() vs base R
Base R provides functions for the same tasks. The dplyr functions can be especially convenient in a pipe-based workflow, while base R is useful when you prefer not to load an additional package.
| Task | dplyr | Base R |
|---|---|---|
| Count rows by region | count(data, region) | as.data.frame(table(data$region)) |
| Return unique regions | distinct(data, region) | unique(data["region"]) |
| Count unique customer IDs | n_distinct(data$customer) | length(unique(data$customer)) |
| Remove duplicate complete rows | distinct(data) | unique(data) |
| Count by two columns | count(data, region, product) | as.data.frame(table(data$region, data$product)) |
One detail to remember: table() may include combinations with zero observations for factor levels or combinations in its dimensions, while count() generally reports combinations observed in the data. Choose the function whose output matches your analytical goal.
13. Common mistakes when using count() and distinct()
| Problem | Why it happens | How to fix it |
|---|---|---|
| Expecting count() to count unique values only | count() counts rows in each category, including repeated values. | Use distinct() for unique values or n_distinct() for their number. |
| Expecting distinct() to return frequencies | distinct() removes repeated keys rather than counting them. | Use count() when you need a frequency column. |
| Removing valid transactions | Repeated customer IDs are mistaken for duplicate rows. | Define what makes a record unique before deduplicating. |
| Keeping the wrong duplicate row | distinct() retains the first matching row in the current order. | Use arrange() before distinct() when the retained row matters. |
| Wrong percentage denominator | Percentages are calculated over all data when they should be within each group, or vice versa. | Calculate the denominator at the level required by the question. |
| Unexpected missing-value counts | Missing values may be counted as a group or ignored by a particular calculation. | Check missing values explicitly and decide how they should be handled. |
14. Practice exercises
Use the sales_data tibble created above. Try writing the code before revealing each answer.
Exercise 1: Count transactions by region
Return the number of transactions in each region.
Show answer
sales_data |>
count(region)
Exercise 2: Find unique region-product combinations
Return each observed combination of region and product once.
Show answer
sales_data |>
distinct(region, product)
Exercise 3: Count unique customers
Calculate the number of unique customer IDs in the whole dataset.
Show answer
sales_data |>
summarise(unique_customers = n_distinct(customer))
Exercise 4: Find customers with multiple transactions
Return customer IDs that appear more than once.
Show answer
sales_data |>
count(customer) |>
filter(n > 1)
Exercise 5: Calculate the percentage of transactions by product
Count transactions by product and add each product's percentage of all transactions.
Show answer
sales_data |>
count(product) |>
mutate(percent = round(100 * n / sum(n), 1))
dplyr FAQ
What does count() do in dplyr?
count() counts the number of rows for each combination of the variables you supply. For example, data |> count(region) returns one row per region and a column named n with the number of rows in each region.
What does distinct() do in R?
dplyr distinct() returns unique rows based on the columns you specify. By default, it keeps all columns for the first row matching each unique combination; use .keep_all = TRUE when you want to identify unique keys while retaining the other columns.
What is the difference between count() and distinct()?
count() reports how many rows belong to each value or combination. distinct() returns the unique values or combinations themselves, without calculating their frequency.
How do I count unique values in R with dplyr?
Use n_distinct() inside summarise(), such as data |> summarise(unique_customers = n_distinct(customer_id)). You can also use distinct(data, customer_id) to return the unique customer IDs as rows.
How do I count rows by group in dplyr?
Use count() with the grouping columns, for example orders |> count(region, product). The result contains one row per region-product combination and a count column named n.
How do I remove duplicate rows with distinct()?
Use distinct(data) to keep unique complete rows, or distinct(data, customer_id, .keep_all = TRUE) to keep the first row for each customer ID while retaining other columns.
How do I sort count() results from largest to smallest?
Use sort = TRUE, as in data |> count(category, sort = TRUE). You can also arrange(desc(n)) after count() for explicit control.
Does distinct() keep the first duplicate?
Yes. When rows share the selected distinct key, distinct() keeps the first matching row in the current order. If which row should be retained matters, arrange the data deliberately before calling distinct().
Key points to remember
- Use
count()to count rows for each value or combination of values. - Use
distinct()to return unique values, combinations or complete rows. - Use
n_distinct()when you need the number of unique values rather than the values themselves. - Use
sort = TRUEorarrange(desc(n))to put the most frequent categories first. - Use
.keep_all = TRUEto retain other columns when selecting unique keys, and arrange first if the retained row matters. - Repeated identifiers do not always mean duplicate records. Understand the unit of observation before removing data.
Continue learning with dplyr case_when() for creating categories using conditions, or revisit group_by() and summarise() for more grouped analysis examples.