which() vs subset()
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: