把函式調到「Purrrfect」
我們仍在調整一個函式,用來偵測一串 URL 清單中是否有無法存取的元素。
先回顧一下目前的程式碼:
- 錯誤擷取器:結合
safely()和map(.x, "error")。 - 「非 null」擷取器:結合
safely()和discard(.x, is.null)。 - 404 產生器:使用
possibly(.x, otherwise = 404),並將其包成函式。
我們要稍微改一下這個函式的行為:你現在希望可以在回傳結果或錯誤之間做選擇。
這樣一來,你就能用同一個函式回答兩個問題:哪些 URL 無法連線?哪些可以連線?為此,你會在這個函式裡加入一個名為「type」的參數。
urls 向量與 safe_read() 已在你的工作環境中可用。
本練習屬於課程
使用 purrr 的 R 語言中級函式程式設計
練習說明
完成函式定義。
- 將
safe_read()對映到 URL 清單。 - 將結果的名稱設為 URL 清單。
- 將結果轉置為包含 $result 與 $error 的清單。
- 使用
pluck()擷取type元素。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Complete the function definition
url_tester <- function(url_list, type = c("result", "error")) {
type <- match.arg(type)
url_list %>%
# Apply safe_read to each URL
___(___) %>%
# Set the names to the URLs
___(___) %>%
# Transpose into a list of $result and $error
___() %>%
# Pluck the type element
___(___)
}
# Try this function on the urls object
url_tester(urls, type = "error")