How to filter data in R?

Coding in R

In R, you can filter data using various functions and logical conditions. Here are a few common ways to filter data:

Using Subsetting

You can use square brackets [] to subset or filter data based on logical conditions.

VBA Code Display
# Create a sample dataframe
df <- data.frame(
Name = c("Alice", "Bob", "Charlie", "David", "Emily"),
    Age = c(25, 30, 22, 35, 28),
    Score = c(80, 90, 75, 95, 85)
    )
            
# Filter data where Age is greater than 25
filtered_data <- df[df$Age > 25, ]
            
# Display the filtered data
print(filtered_data)

Using subset() Function

The subset() function is another way to filter data based on conditions.

VBA Code Display
# Using subset to filter data
filtered_data <- subset(df, Age > 25)
            
# Display the filtered data
print(filtered_data)

Using dplyr Package

The dplyr package provides a convenient and expressive syntax for data manipulation. Here’s an example using filter() function:

VBA Code Display
# Install and load the dplyr package
install.packages("dplyr")
library(dplyr)
            
# Filter data using dplyr
filtered_data <- df %>%
filter(Age > 25)
            
# Display the filtered data
print(filtered_data)

Choose the method that suits your preference and coding style. Adjust the conditions based on your specific filtering requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top