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

subset()

subset picks out only the rows of a table that meet a rule, like pulling out all the cards of one color. You describe the rule and get a smaller table.

In this page:

  1. subset()
Syntax
r
subset(df, condition)
subset(df, condition, select = c(column1, column2))

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)
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. Putting the column name in quotes, such as subset(df, "age" >= 30), which compares text with a number.
  2. Using subset() inside functions or packages, where lookups of variables can behave unexpectedly, when df[df$age >= 30, ] is safer.
  3. Using && instead of & to combine conditions, which does not work on whole columns.
🔒

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.