2015年7月25日 星期六

Windows上建置R Studio與Package安裝

上午上R Crawler課程,記錄在Windows安裝R Studio環境,要注意的細節。
Step 1. 到R 官網,下載安裝 R for Windows
Step 2. 到R Studio官網,下載安裝 R Studio

Step 3. 在Console畫面中輸入以下指令,安裝套件。
install.packages("httr")
install.packages("XML")
install.packages("tmcn", repos="http://R-Forge.R-project.org")
install.packages("devtools")
install.packages("http://cran.r-project.org/src/contrib/Archive/CSS/CSS_1.0.2.tar.gz",repos = NULL,type = "source")

安裝套件後檢查一下,出現以下有套件無法安裝的訊息

這時可到 R-Forge 官網下載 "tmcn" 套件,回到RStudio 右下角視窗中,點選 "Packages" 標籤頁中的 "Install"。

在對話框中 "Install from" 項目中,選擇 "Package Archive File (.zip;,tar.gz)" 選項,並在 "Package Archive" 項目中,找到剛剛下載 "tmcn" 套件 "tmcn_0.1-4.zip" 來安裝。

最後 "tmcn" 套件安裝成功的畫面。

PS:"tmcn" 套件為Windows上用來處理中文字的套件,有需要在Windows上處理中文字的朋友可以多注意。

Step 4. 輸入以下程式碼,開始用R抓網頁資料。
library(httr);
library(XML);
library(tmcn);
req <- GET("https://tw.news.yahoo.com/sports/",encoding='utf8')
req <- content(req,'text', encoding = 'utf8')
req <- htmlParse(req, encoding = 'utf8')
dd <- xpathSApply(req, '//div[@id="mediablistmixedlpcatemp"]/div/ul/li/div/a', xmlValue)
View(dd)