← Back to R Course | Chapter 12: Best Practices | Lesson 3 of 6

which() vs subset()

which and subset both find things that match a rule, but which gives you the positions while subset gives you the actual rows. It is like asking for seat numbers versus asking for the people.

In this page:

  1. which() vs subset()
Syntax
r
vector_name[which(condition)]
subset(df, condition)

which() vs subset()

which() returns indices matching a condition and works on any vector, while subset() is specifically for filtering rows of a data frame using column names directly.

Use df[which(df$col > x), ] or the simpler df[df$col > x, ] for basic filtering, and reach for subset() when you also want to select specific columns at the same time. Both express the same filtering intent with slightly different syntax and use cases.

Note:
  • For a plain vector, use which().
  • For filtering rows of a data frame, subset() or direct df[condition, ] indexing is more idiomatic.

Example: which() vs subset()

markup
df <- data.frame(name = c("Alice", "Bob", "Cara"), age = c(30, 25, 40))

cat("Using which():\n")
print(df[which(df$age > 28), ])

cat("Using subset():\n")
print(subset(df, age > 28))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using which() with NA in the data and expecting the NA rows to appear, when they are dropped.
  2. Using subset() in programming code and getting unexpected results, when it evaluates columns in a special way.
  3. Expecting which(df$age > 28) to return rows, when it returns positions that must be used as df[..., ].
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.