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] 2Combine 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
EasyComplete 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler