
- R 教程
- R - 首頁
- R - 概述
- R - 環境設定
- R - 基本語法
- R - 資料型別
- R - 變數
- R - 運算子
- R - 決策制定
- R - 迴圈
- R - 函式
- R - 字串
- R - 向量
- R - 列表
- R - 矩陣
- R - 陣列
- R - 因子
- R - 資料框
- R - 包
- R - 資料重塑
R - 網路資料
許多網站提供資料供其使用者使用。例如,世界衛生組織 (WHO) 以 CSV、txt 和 XML 檔案的形式提供有關健康和醫療資訊的報告。使用 R 程式,我們可以以程式設計方式從這些網站提取特定資料。R 中用於從網路抓取資料的某些包包括 - “RCurl”、“XML”和“stringr”。它們用於連線 URL、識別檔案的所需連結並將它們下載到本地環境。
安裝 R 包
處理 URL 和檔案連結需要以下包。如果您的 R 環境中沒有它們,您可以使用以下命令安裝它們。
install.packages("RCurl") install.packages("XML") install.packages("stringr") install.packages("plyr")
輸入資料
我們將訪問 URL 天氣資料 並使用 R 下載 2015 年的 CSV 檔案。
示例
我們將使用函式 getHTMLLinks() 收集檔案的 URL。然後,我們將使用函式 download.file() 將檔案儲存到本地系統。由於我們將對多個檔案重複使用相同的程式碼,因此我們將建立一個函式以多次呼叫。檔名以 R 列表物件的形式作為引數傳遞給此函式。
# Read the URL. url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/" # Gather the html links present in the webpage. links <- getHTMLLinks(url) # Identify only the links which point to the JCMB 2015 files. filenames <- links[str_detect(links, "JCMB_2015")] # Store the file names as a list. filenames_list <- as.list(filenames) # Create a function to download the files by passing the URL and filename list. downloadcsv <- function (mainurl,filename) { filedetails <- str_c(mainurl,filename) download.file(filedetails,filename) } # Now apply the l_ply function and save the files into the current R working directory. l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/")
驗證檔案下載
執行上述程式碼後,您可以在當前 R 工作目錄中找到以下檔案。
"JCMB_2015.csv" "JCMB_2015_Apr.csv" "JCMB_2015_Feb.csv" "JCMB_2015_Jan.csv" "JCMB_2015_Mar.csv"
廣告