← Back to R Course | Chapter 8: Data Manipulation | Lesson 3 of 7

subset()

In this page:

  1. subset()

subset()

subset(df, condition) filters a data frame's rows based on a logical condition, similar to a SQL WHERE clause. It also accepts a select argument to choose specific columns at the same time. subset() is a convenient shorthand over the more verbose df[df$col > x, ] indexing syntax.

Note: subset()'s condition can reference column names directly, without needing df$ prefixes, unlike standard bracket indexing.

Example: subset()

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

adults <- subset(df, age >= 30)
print(adults)

names_only <- subset(df, age >= 30, select = name)
print(names_only)
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.