The filter() function helps you pick only the rows you want from a table based on conditions. It makes your data smaller and focused.
0
0
filter() for row selection in R Programming
Introduction
You want to see only the students who scored above 80 in a test.
You need to find all sales records from last month.
You want to select only the rows where a product is in stock.
You want to analyze data for a specific city or region.
Syntax
R Programming
filter(data_frame, condition1, condition2, ...)data_frame is your table of data.
Conditions decide which rows to keep. Use logical operators like && (and), || (or), and comparison operators like ==, >, <.
Examples
Selects rows where the age column is greater than 30.
R Programming
filter(df, age > 30)
Selects rows where city is New York and score is at least 90.
R Programming
filter(df, city == "New York", score >= 90)
Selects rows where gender is female or other.
R Programming
filter(df, gender == "female" | gender == "other")
Sample Program
This program creates a table of students with their age, city, and score. Then it uses filter() to pick only students older than 30. Finally, it prints those students.
R Programming
library(dplyr) # Create a sample data frame students <- data.frame( name = c("Alice", "Bob", "Carol", "David"), age = c(25, 32, 28, 40), city = c("New York", "Chicago", "New York", "Boston"), score = c(88, 75, 92, 85) ) # Select students older than 30 older_students <- filter(students, age > 30) print(older_students)
OutputSuccess
Important Notes
Make sure to load the dplyr package before using filter().
Conditions inside filter() can be combined with commas (meaning AND) or logical operators.
If no rows match the condition, filter() returns an empty data frame.
Summary
filter() helps you pick rows from a table based on rules.
You can use one or more conditions to select exactly what you want.
Remember to load dplyr to use filter().