filter rows that match values on two columns in a dataframe in r

To filter rows that match values on two columns in a DataFrame in R, you can use the following methods:

Method 1: Using Base R

You can use the following code to filter rows based on two columns:

main.r
# create a sample dataframe
df <- data.frame(
  id = c(1, 2, 3, 4, 5),
  name = c("John", "Mary", "John", "Mary", "Tom"),
  age = c(25, 31, 25, 31, 42)
)

# filter rows where name is 'John' and age is 25
filtered_df <- df[df$name == "John" & df$age == 25, ]

# print the filtered dataframe
print(filtered_df)
309 chars
13 lines

Method 2: Using Dplyr

You can also use the dplyr package to filter rows:

main.r
# install and load dplyr package
install.packages("dplyr")
library(dplyr)

# create a sample dataframe
df <- data.frame(
  id = c(1, 2, 3, 4, 5),
  name = c("John", "Mary", "John", "Mary", "Tom"),
  age = c(25, 31, 25, 31, 42)
)

# filter rows where name is 'John' and age is 25
filtered_df <- df %>% 
  filter(name == "John" & age == 25)

# print the filtered dataframe
print(filtered_df)
390 chars
18 lines

Both methods will produce the same output:

main.r
  id name age
1  1 John  25
2  3 John  25
42 chars
4 lines

related categories

gistlibby LogSnag