Delete Rows in R with Conditions


Do you need to delete (or drop) some rows in your R dataset that meet certain conditions.

Below is an example. The data frame is called df. Here we need to remove rows that have a negative value for ride_length.

df_v2 <- df[!(df$start_station_name == "HQ QR" | all_trips$ride_length<0),]

Here is a website that describes how to do that. The article is called DELETE OR DROP ROWS IN R WITH CONDITIONS.

Let’s look at this with a more simple example. We’ll use our simple small friends data set. Let’s create that.

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

Let’s delete friends that are over 41 years of age. Sorry about that. We want friends that are 41 and younger.

friends_2 <- friends[(friends$age < 42),]

Leave a Reply