Filtering a Data Set in R


How do you filter a data set in R? Suppose you want to only see certain rows of your data set. You have a condition that restricts the list of people to those who are 40 years old. You have a list of friends in a data set called friends. One of the columns is called age.

Let’s use RStudio for this. We will create our data frame manually in R code as shown below.

library(skimr)
name <- c("Bob", "Sally", "Pierre", "Pat")
age <- c(40, 41, 42, 40)
gender <- c("M", "F", "M", "F")
friends <- data.frame(name, age, gender)
View(friends)

friends_40 = friends[(friends$age == 40),]   # 40
View(friends_40)

friends_4041 = friends[(friends$age == 40) | (friends$age == 41),]   # 40 or 41
View(friends_4041)

Check out the filter function.

Leave a Reply