R 沒有獨立的集合資料型態,而是用各種函式對向量執行類似的操作。
%in%運算子用來測試元素是否屬於某個集合。
2 %in% 1:10 # TRUE
12 %in% 1:10 # FALSE
相關的函式包括unique(移除重複的元素),以及用來處理成對集合的union()、intersect()、setdiff()和setequal()。
> set_1 <- c("a", "b", "c", "b", "a")
> unique(set_1) # deduplicate
[1] "a" "b" "c"
> set_2 <- c('a', "c", "d")
> union(set_1, set_2) # values in either set
[1] "a" "b" "c" "d"
> intersect(set_1, set_2) # values in both sets
[1] "a" "c"
> setdiff(set_1, set_2) # values in set_1 but not set_2
[1] "b"
> setdiff(set_2, set_1) # values in set_2 but not set_1
[1] "d"
setequal(set_1, c("c", "b", "a", "b")) # are elements the same after deduplication?
[1] TRUE
在上述每個情況下,set_1和set_2都不會被改變。
Ozan 正在為即將到來的公路旅行整理播放清單。他不想重複聽到同一首曲目,但播放清單已經長到他記不得哪些曲目已經加過了。
Ozan 的音樂播放器 API 只懂得處理向量。無法使用明確的迴圈或 if/else 邏輯。他需要你的幫忙!
實作remove_duplicates函式,它接受一個播放清單作為_參數_,並_回傳_一個所有曲目都不重複的新播放清單。
> playlist <- c(
"Court and Spark - Joni Mitchell",
"Big Yellow Taxi - Joni Mitchell",
"Court and Spark - Joni Mitchell"
)
> remove_duplicates(playlist)
[1] "Court and Spark - Joni Mitchell" "Big Yellow Taxi - Joni Mitchell"
實作has_track函式,它接受一個播放清單和一首曲目作為_參數_,並_回傳_一個布林值,表示播放清單是否包含該曲目。
> playlist <- c(
"The Fashion Show - Grace Jones",
"Dr. Funkenstein - Parliament"
)
> has_track(playlist, "Dr. Funkenstein - Parliament")
[1] TRUE
> has_track(playlist, "Walking in the Rain - Grace Jones")
[1] FALSE
實作add_tracks函式,它接受一個播放清單和一個包含一或多首曲目的向量作為_參數_,並_回傳_一個包含這些曲目的新播放清單。
> playlist <- c("Selma - Bijelo Dugme")
> playlist <- add_tracks(playlist, "Atomic Dog - George Clinton")
> playlist
[1] "Selma - Bijelo Dugme" "Atomic Dog - George Clinton"
> add_tracks(playlist, "Selma - Bijelo Dugme")
[1] "Selma - Bijelo Dugme" "Atomic Dog - George Clinton"
> add_tracks(playlist, c("The Chain - Fleetwood Mac", "Selma - Bijelo Dugme"))
[1] "Selma - Bijelo Dugme" "Atomic Dog - George Clinton" "The Chain - Fleetwood Mac"
實作delete_tracks函式,它接受一個播放清單和一或多首曲目作為_參數_,並_回傳_一個不包含這些曲目的新播放清單。
> playlist <- c(
"The Treasure - Fra Lippo Lippi",
"After the Fall - Klaus Nomi"
)
> playlist <- delete_tracks(playlist, "The Treasure - Fra Lippo Lippi")
> playlist
[1] "After the Fall - Klaus Nomi"
> delete_tracks(playlist, "I Feel the Magic - Belinda Carlisle")
[1] "After the Fall - Klaus Nomi"
Ozan 認識了一位新朋友,想知道彼此的音樂品味有多相近。
實作find_common_tracks函式,它接受兩個播放清單,回傳一個只包含兩者共同曲目的新播放清單。
> playlist_1 <- c("Karma - Taylor Swift", "Tired - Adele")
> playlist_2 <- c("Andromeda - Weyes Blood", "Karma - Taylor Swift")
> find_common_tracks(playlist_1, playlist_2)
[1] "Karma - Taylor Swift"