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

which() vs subset()

In this page:

  1. which() vs subset()

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))
🔒

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.