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:
Syntax
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()
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)
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
- Putting the column name in quotes, such as
subset(df, "age" >= 30), which compares text with a number. - Using
subset()inside functions or packages, where lookups of variables can behave unexpectedly, whendf[df$age >= 30, ]is safer. - 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: