Filter Rows Based on Conditions in a DataFrame in R

Here are several ways to filter rows based on conditions in a DataFrame in R:

(1) Filter rows based on a single condition:

To maintain only the rows where the price is greater than 400:

df <- data.frame(product = c("laptop", "printer", "tablet", "desk", "chair"),
                 brand = c("A", "B", "X", "Y", "Z"),
                 price = c(1200, 150, 300, 450, 200)
                 )

df_filtered <- df[df$price > 400, ]

print(df_filtered)

As you can see, only the rows, where the price is greater than 400, are kept:

  product  brand  price
1  laptop      A   1200
4    desk      Y    450

(2) Filter rows based on multiple conditions:

To maintain only the rows where the price is greater than 400 AND the brand is “A”:

df <- data.frame(product = c("laptop", "printer", "tablet", "desk", "chair"),
                 brand = c("A", "B", "X", "Y", "Z"),
                 price = c(1200, 150, 300, 450, 200)
                 )

df_filtered <- df[df$price > 400 & df$brand == "A", ]

print(df_filtered)

Now only the laptop product fulfills these conditions:

  product  brand  price
1  laptop      A   1200

Alternatively, to keep only the rows where the brand is either “A” or “X”:

df <- data.frame(product = c("laptop", "printer", "tablet", "desk", "chair"),
                 brand = c("A", "B", "X", "Y", "Z"),
                 price = c(1200, 150, 300, 450, 200)
                 )

df_filtered <- df[df$brand %in% c("A", "X"), ]

print(df_filtered)

The result:

  product  brand  price
1  laptop      A   1200
3  tablet      X    300

Leave a Comment