Unique Values
Part of the Logic & Flow section of Coddy's R journey. Lesson 12 of 64.
R has no separate set type: a set is a vector without repeated values. unique() removes the repeats and keeps the first occurrence of each value, in the original order.
tags <- c("r", "stats", "r", "data", "stats")
print(unique(tags))
print(length(unique(tags)))Output:
[1] "r" "stats" "data"
[1] 3duplicated() returns TRUE for every value that already appeared earlier in the vector. The first occurrence is FALSE:
ids <- c(7, 3, 7, 9, 3)
print(duplicated(ids))
print(ids[duplicated(ids)])Output:
[1] FALSE FALSE TRUE FALSE TRUE
[1] 7 3Both functions compare exact values, so "R" and "r" are different. Normalize the text first when case should not matter:
langs <- c("R", "python", "r", "Python")
print(length(unique(langs)))
print(unique(tolower(langs)))Output:
[1] 4
[1] "r" "python"unique() works on numbers too, and sort(unique(x)) lists the distinct values in increasing order. sum(duplicated(x)) counts how many elements are repeats:
rolls <- c(4, 2, 6, 2, 4, 4)
print(sort(unique(rolls)))
print(sum(duplicated(rolls)))Output:
[1] 2 4 6
[1] 3Challenge
EasyComplete count_distinct(tags). Return how many different tags there are when case is ignored: R and r count once.
The supplied code reads the tags as a comma-separated line and prints the returned number.
Try it yourself
count_distinct <- function(tags) {
# Write your code here
0
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(count_distinct(strsplit(input[1], ",")[[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