Menu
Coddy logo textTech

Filtering Rows

Part of the Logic & Flow section of Coddy's R journey. Lesson 44 of 64.

A logical vector with one value per row selects the rows where it is TRUE. Put it before the comma, and keep the column side empty to keep every column:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
print(people[people$age > 30, ])
print(nrow(people[people$age > 30, ]))

Output:

  name age   city
1  ada  36 london
3   cy  41   rome
[1] 2

Combine conditions with & (both) and | (either). Each part compares a whole column, so the result still has one value per row:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
print(people[people$age > 30 & people$city == "london", ])
print(people$name[people$age < 25 | people$city == "rome"])

Output:

  name age   city
1  ada  36 london
[1] "bo" "cy"

subset(df, condition) does the same with shorter code, because inside it the column names can be used directly:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
older <- subset(people, age > 30)
print(older$name)

Output:

[1] "ada" "cy" 

When no row matches, the result is a data frame with 0 rows, so check nrow() before reading from it:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
nobody <- people[people$age > 90, ]
print(nrow(nobody))
print(if (nrow(nobody) == 0) "none" else nobody$name[1])

Output:

[1] 0
[1] "none"
challenge icon

Challenge

Easy

Complete adults_in(df, city). df has the columns name, age and city. Return the names of the people who are at least 18 and live in city, in row order and joined with , , or none.

The supplied code reads the table from the input with read.csv(text = input): the first line holds the column names and every following line is one row, with values separated by commas. The last input line holds the city, and the code prints the returned value.

Try it yourself

adults_in <- function(df, city) {
  # Write your code here
  "none"
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
df <- read.csv(text = input[-length(input)])
cat(adults_in(df, input[length(input)]), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler