R subset()
Published Oct 7, 2022
Contribute to Docs
The subset() function returns a subset of a data frame that matches the specified conditions.
Syntax
subset(df_object, expression)
- The
df_objectparameter is the data frame to retrieve the subset from. - The
expressionspecifies the subset conditions.
Example
The following example uses a CSV file named inventory.csv with the following information in it:
| Item | Quantity | Cost |
|---|---|---|
| Hoodies | 58 | 25 |
| Pens | 80 | 1.5 |
| Pencil | 75 | 0.88 |
| T-shirts | 100 | 15 |
The subset() function can be used to get the subset of items where the Cost is greater than 10:
# Read filedf <- read.csv("inventory.csv")# Retrieve subsetsubset(df, Cost > 10)
The example returns the following:
Item Quantity Cost1 Hoodies 58 254 T-shirts 100 15
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn R on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn how to code and clean and manipulate data for analysis and visualization with the R programming language.
- Beginner Friendly.14 hours