R Count Number Of Occurrences In Column

8 min read

Counting how many times a value appears in a column is one of the most common tasks in data analysis with R. Whether you are tallying survey responses, checking for duplicate entries, or summarizing categorical variables, knowing how to count the number of occurrences in a column in R quickly and accurately will save you hours of manual work. Also, this guide walks through every practical method — from base R functions to modern dplyr and data. table approaches — with clear examples you can copy and adapt to your own datasets.

Why Counting Occurrences Matters in Data Analysis

Before diving into syntax, it helps to understand why this operation is so fundamental. Counting occurrences in a column allows you to:

  • Validate data quality by spotting unexpected duplicates or missing values.
  • Summarize categorical variables such as gender, city, or product category.
  • Build frequency tables that feed into charts and reports.
  • Filter datasets by keeping only rows whose values appear a certain number of times.
  • Detect anomalies like a customer ID appearing far more often than expected.

In short, frequency counting is the backbone of exploratory data analysis. Let's build a small example dataset and use it throughout the article And that's really what it comes down to..

# Create a sample data frame
df <- data.frame(
  id = 1:10,
  city = c("Jakarta", "Bandung", "Jakarta", "Surabaya",
           "Bandung", "Jakarta", "Medan", "Surabaya",
           "Jakarta", NA),
  score = c(80, 90, 80, 70, 90, 85, 70, 70, 95, 60)
)

Method 1: Using table() in Base R

The table() function is the fastest way to count occurrences of every unique value in a column. It returns a named vector where names are the unique values and numbers are their frequencies.

table(df$city)

Output:

Bandung  Jakarta    Medan Surabaya
      2        4        1        2

This is ideal for a quick overview. If you want the result as a data frame for further processing, wrap it:

as.data.frame(table(df$city))

Tip: By default, table() excludes NA values. Add useNA = "ifany" to include them:

table(df$city, useNA = "ifany")

Method 2: Counting a Specific Value with sum()

If you only need the count of one particular value, logical comparison combined with sum() is the most efficient approach. In R, TRUE equals 1 and FALSE equals 0, so summing a logical vector gives you the count.

sum(df$city == "Jakarta")        # 4
sum(df$city == "Jakarta", na.rm = TRUE)  # safer with NA present

You can also use length() with which():

length(which(df$city == "Jakarta"))

Both return the same result, but sum() is generally faster and more readable. For numeric conditions, the same logic applies:

sum(df$score >= 80)   # count rows scoring 80 or above

Method 3: The dplyr Approach with count() and n()

The dplyr package, part of the tidyverse, offers the most readable syntax for counting occurrences. The count() function does the heavy lifting in a single line Practical, not theoretical..

library(dplyr)

df %>% count(city)

This returns a tibble with a city column and an n column showing frequencies. To sort by frequency:

df %>% count(city, sort = TRUE)

You can also count within groups using group_by() and summarise():

df %>%
  group_by(city) %>%
  summarise(total = n())

The n() function counts rows per group, while sum(!is.na(city)) counts non-missing values specifically.

df %>%
  group_by(city) %>%
  summarise(
    total_rows = n(),
    high_scores = sum(score >= 80)
  )

Method 4: Counting with data.table

For large datasets, data.The .table is unbeatable in speed. N symbol represents the number of rows in each group.

library(data.table)
dt <- as.data.table(df)

dt[, .N, by = city]

To count a specific value directly:

dt[city == "Jakarta", .N]

This syntax is concise and extremely fast on millions of rows, making it a favorite among analysts working with big data Easy to understand, harder to ignore..

Method 5: Counting Substring Occurrences in Text Columns

Sometimes you need to count how many times a word or pattern appears inside text values, not how many rows match exactly. The stringr package handles this elegantly.

library(stringr)

# Count rows where the city name contains "a"
sum(str_detect(df$city, "a"), na.rm = TRUE)

# Count total occurrences of a pattern across all strings
sum(str_count(df$city, "a"), na.rm = TRUE)

The difference is important: str_detect() returns one logical value per row, while str_count() returns the number of matches within each string. Summing str_count() gives the total number of pattern occurrences across the entire column.

Method 6: Counting Duplicates and Repeated Values

A frequent real-world need is identifying which values appear more than once. Combine table() with logical filtering:

freq <- table(df$city)
freq[freq > 1]

Or with dplyr, filter after counting:

df %>%
  count(city) %>%
  filter(n > 1)

To flag duplicates in the original data frame, use duplicated() or add_count():

df %>% add_count(city, name = "occurrences")

This adds a column showing how many times each city appears, without collapsing the data frame — perfect for further filtering.

Handling Missing Values Correctly

Missing values are the most common source of wrong counts. Remember these rules:

  • table() ignores NA unless you set useNA = "ifany".
  • sum() returns NA if any element is NA unless you add na.rm = TRUE.
  • dplyr::count() includes NA as its own category by default.
  • n() counts all rows, including those with missing values in other columns.

Always check with sum(is.na(df$city)) before trusting your frequency counts That's the part that actually makes a difference. Practical, not theoretical..

Quick Comparison of Methods

Method Best For Speed
table() Quick frequency tables Fast
sum(x == value) Single value counts Very fast
dplyr::count() Readable pipelines Fast
data.table Large datasets Fastest
stringr Text pattern counting Moderate

The official docs gloss over this. That's a mistake Easy to understand, harder to ignore..

Frequently Asked Questions

How do I count occurrences of multiple values at once? Use %in% with sum(): sum(df$city %in% c("Jakarta", "Bandung")). This counts rows matching any value in the vector The details matter here..

How can I count occurrences across multiple columns?

How can I count occurrences across multiple columns?

For multi-column counting, you can use dplyr to create a unified condition. As an example, to count rows where either city is "Jakarta" or status is "Active":

df %>%
  filter(city == "Jakarta" | status == "Active") %>%
  nrow()

Or, if you want to count occurrences of a pattern across multiple text columns, combine stringr functions with rowSums:

# Count total occurrences of "a" in both 'city' and 'description' columns
sum(rowSums(sapply(df[, c("city", "description")], function(col) 
  stringr::str_count(col, "a", na.rm = TRUE))), na.rm = TRUE)

Conclusion

Counting occurrences in R is a fundamental skill that becomes intuitive with practice. That said, whether you need simple value counts, pattern matches, or duplicate analysis, R provides efficient tools for every scenario. The key is choosing the right method for your data size and question type — table() for quick overviews, data.table for massive datasets, and stringr for text patterns. Always remember to handle missing values explicitly to ensure accurate results. With these techniques, you'll be able to extract meaningful insights from your data efficiently.

Easier said than done, but still worth knowing.

How do I count occurrences grouped by multiple variables?

Pass several grouping columns to count(). This gives you a frequency table for every combination:

df %>% count(city, status, sort = TRUE)

The sort = TRUE argument arranges results from most to least frequent, which is handy when you only care about the top combinations.

How do I count unique values instead of total rows?

Combine n_distinct() with summarise():

df %>% summarise(unique_cities = n_distinct(city))

To count distinct values within groups, add a group_by() first:

df %>% group_by(status) %>% summarise(unique_cities = n_distinct(city))

How can I count occurrences efficiently on very large data?

For datasets with millions of rows, data.table outperforms the alternatives because it modifies data by reference:

library(data.table)
setDT(df)[, .N, by = city]        # counts per city
setDT(df)[, .N, by = .(city, status)]  # grouped counts

The .N symbol is a built-in variable that holds the number of rows in each group, making this one of the fastest counting idioms in R.

Common Pitfalls to Avoid

Even experienced R users trip over these:

  • Comparing with == against factors. Convert to character first with as.character() to avoid unexpected mismatches.
  • Forgetting na.rm = TRUE. A single NA can silently turn your count into NA.
  • Assuming == is vector-safe in if(). Wrap it in any() or all() when you need a single logical result.
  • Counting substrings vs. whole values. sum(x == "a") counts exact matches, while str_count(x, "a") counts every occurrence within each string. These give very different answers.

Conclusion

Counting occurrences in R comes down to matching the tool to the question. Also, reach for sum(x == value) when you need a single count, table() for a quick frequency overview, dplyr::count() for readable grouped pipelines, and data. table when performance matters on large data. On top of that, for text patterns, stringr::str_count() is the go-to. But whatever method you choose, handle missing values deliberately and verify your assumptions with a quick is. na() check. Still, master these few functions and you will be able to answer almost any "how often does this happen? " question your data throws at you.

Fresh Out

Fresh Stories

People Also Read

We Picked These for You

Thank you for reading about R Count Number Of Occurrences In Column. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home