用 keep() 和 discard() 分組
我們要把結果分成兩組:大於 100 的天數,和小於 100 的天數。為了達成這個目標,會同時使用 keep() 和 discard()。
為什麼要兩個函式?不能只用一個嗎?不能建立一個叫做 is_less_than_hundred 的 mapper 嗎?
可以,但那樣比較容易出錯:從
keep()換成discard()比複製貼上還容易。把兩個函式搭配使用,我們只需要一個 mapper。也就是說,如果想調整門檻值,只要改一次就好;若用兩個 mapper,則得改兩次。
這是寫程式時應該力行的原則:讓程式碼在需要改動時,只要改一處就能生效。
all_visits 仍然可在你的工作空間中使用。
本練習屬於課程
使用 purrr 的 R 語言中級函式程式設計
練習說明
- 將
set_names()套用到all_visits,把星期名稱加上去,存成all_visits_named。 - 建立一個名為
threshold的 mapper,用來測試.x是否大於 100。 - 以保留大於 100 的元素,建立
group_over。 - 以丟棄大於 100 的元素,建立
group_under。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Set the name of each subvector
day <- c("mon", "tue", "wed", "thu", "fri", "sat", "sun")
all_visits_named <- ___(all_visits, ~ ___(.x, ___))
# Create a mapper that will test if .x is over 100
threshold <- ___
# Run this mapper on the all_visits_named object: group_over
group_over <- ___(all_visits_named, ~ ___(.x, ___))
# Run this mapper on the all_visits_named object: group_under
group_under <- ___(all_visits_named, ~ ___(.x, ___))