Menu
Coddy logo textTech

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] 3

duplicated() 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 3

Both 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] 3
challenge icon

Challenge

Easy

Complete 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")
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