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:
Syntax
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()
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))
Login to try C/C++/Java/PHP code in the editor
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
- Using
which()withNAin the data and expecting theNArows to appear, when they are dropped. - Using
subset()in programming code and getting unexpected results, when it evaluates columns in a special way. - Expecting
which(df$age > 28)to return rows, when it returns positions that must be used asdf[..., ].
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: