0
0
R Programmingprogramming~5 mins

Filtering rows in R Programming

Choose your learning style9 modes available
Introduction

Filtering rows helps you pick only the data you want from a table. It makes your data easier to understand and work with.

You want to see only sales from a specific city.
You need to find students who scored above 80 in a test.
You want to analyze data from a certain year.
You want to remove rows with missing or unwanted values.
Syntax
R Programming
filtered_data <- subset(data, condition)

data is your original table or data frame.

condition is a rule that rows must follow to be kept.

Examples
This keeps rows where the Age column is greater than 30.
R Programming
filtered_data <- subset(df, Age > 30)
This keeps rows where the City column is exactly "New York".
R Programming
filtered_data <- subset(df, City == "New York")
This keeps rows where Score is at least 50 and Passed is TRUE.
R Programming
filtered_data <- subset(df, Score >= 50 & Passed == TRUE)
Sample Program

This program creates a small table with names, ages, and cities. Then it keeps only the rows where Age is more than 30 and City is "New York". Finally, it prints the filtered table.

R Programming
df <- data.frame(Name = c("Anna", "Ben", "Cara", "Dan"), Age = c(25, 35, 30, 40), City = c("New York", "New York", "New York", "Boston"))
filtered_df <- subset(df, Age > 30 & City == "New York")
print(filtered_df)
OutputSuccess
Important Notes

You can use logical operators like & (and), | (or), and ! (not) in conditions.

Make sure your condition matches the column names exactly, including case.

Filtering does not change the original data unless you save the result back.

Summary

Filtering rows helps you focus on the data you need.

Use subset() with a condition to pick rows.

Combine conditions with & and | for more control.