Set Operations
Part of the Logic & Flow section of Coddy's R journey. Lesson 13 of 64.
Three functions combine two vectors as sets. Each returns values without repeats:
union(a, b) has the values in either vector, intersect(a, b) the values in both, and setdiff(a, b) the values of a that are not in b.
mon <- c("ana", "ben", "cy")
tue <- c("ben", "dee", "cy", "ben")
print(union(mon, tue))
print(intersect(mon, tue))
print(setdiff(mon, tue))Output:
[1] "ana" "ben" "cy" "dee"
[1] "ben" "cy"
[1] "ana"setdiff() depends on the order of its arguments. Swap them to get the values that are only in the second vector:
mon <- c("ana", "ben", "cy")
tue <- c("ben", "dee", "cy")
print(setdiff(tue, mon))Output:
[1] "dee"When nothing is left, the result is an empty vector, character(0) for text:
print(intersect(c("a", "b"), c("x", "y")))Output:
character(0)The results keep the order of the first vector. Sort them when the output needs a predictable order, and check for an empty result before joining:
a <- c("pear", "fig", "kiwi")
b <- c("kiwi", "pear")
both <- sort(intersect(a, b))
print(paste(both, collapse = ", "))
print(length(setdiff(b, a)) == 0)Output:
[1] "kiwi, pear"
[1] TRUEChallenge
EasyComplete compare_courses(a, b). a and b are the students of two courses. Return three lines:
Both:followed by the students in both coursesOnly first:followed by the students only inaTotal:followed by the number of different students across both courses
Sort the names in each list and join them with , . An empty list is written none.
The supplied code reads the two courses as comma-separated lines and prints each returned line.
Try it yourself
compare_courses <- function(a, b) {
# Write your code here
c("Both: ", "Only first: ", "Total: 0")
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(compare_courses(strsplit(input[1], ",")[[1]], strsplit(input[2], ",")[[1]]), 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