建構一個函式
你正在持續精進你的網頁擷取工具,好讓你在網頁代理商擔任資料分析師時能更有效率地完成工作。
在這個練習中,你會把上一題的擷取函式再嚴謹一點:如果狀態擷取器回傳的代碼不在 200 到 203 之間,函式就回傳遺漏值(NA)。否則,就回傳該狀態代碼。
purrr 與 httr 已為你載入。
本練習屬於課程
使用 purrr 的 R 語言中級函式程式設計
練習說明
反向化
%in%運算子。它用來測試左側元素是否包含在右側元素中。組合一個
extract_status()函式,將GET()與status_code()串接在一起。完成給定的函式:先擷取
url的狀態代碼並指定給變數code。接著,如果這個code不在200:203中,就回傳遺漏值;否則回傳該狀態代碼。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Negate the %in% function
`%not_in%` <- ___(`%in%`)
# Compose a status extractor
extract_status <- ___(___, ___)
# Complete the function definition
strict_code <- function(url) {
# Extract the status of the URL
code <- ___(___)
# If code is not in the acceptable range ...
if (code ___ 200:203) {
# then return NA
return(___)
}
code
}