使用R 讀取csv檔案

getwd()
## [1] "C:/Users/USER/Desktop"
#?download.file
download.file('https://raw.githubusercontent.com/ywchiu/rtibame/master/Data/purchase.csv', destfile = 'purchase.csv')
purchase <- read.csv('purchase.csv')

# 檢視數據
class(purchase)
## [1] "data.frame"
str(purchase)
## 'data.frame':    54772 obs. of  7 variables:
##  $ X       : int  0 1 2 3 4 5 6 7 8 9 ...
##  $ Time    : Factor w/ 53387 levels "2015-07-01 00:00:01",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ Action  : Factor w/ 1 level "order": 1 1 1 1 1 1 1 1 1 1 ...
##  $ User    : Factor w/ 32539 levels "U1000001354",..: 8750 7126 187 7952 8235 19731 21996 13919 21994 8700 ...
##  $ Product : Factor w/ 20054 levels "P0000005913",..: 7731 6487 2370 12645 12183 4228 10469 4506 537 7731 ...
##  $ Quantity: int  1 1 1 1 1 1 1 1 1 1 ...
##  $ Price   : num  1069 1680 285 550 249 ...
head(purchase)
##   X                Time Action         User        Product Quantity Price
## 1 0 2015-07-01 00:00:01  order   U312622727    P0006944501        1  1069
## 2 1 2015-07-01 00:00:03  order   U239012343    P0006018073        1  1680
## 3 2 2015-07-01 00:00:19  order U10007697373    P0002267974        1   285
## 4 3 2015-07-01 00:01:10  order   U296328517    P0016144236        1   550
## 5 4 2015-07-01 00:01:36  order   U300884570 P0014516980122        1   249
## 6 5 2015-07-01 00:01:48  order   U451050374    P0004134266        1  1780
tail(purchase)
##           X                Time Action       User        Product Quantity
## 54767 54766 2015-07-30 23:58:32  order U481290318    P0024913254        1
## 54768 54767 2015-07-30 23:58:53  order  U18517004    P0006036273        1
## 54769 54768 2015-07-30 23:59:24  order U217552746    P0010409991        1
## 54770 54769 2015-07-30 23:59:33  order U395036534    P0025123755        1
## 54771 54770 2015-07-30 23:59:37  order  U14085643 P0009890670031        1
## 54772 54771 2015-07-30 23:59:56  order  U33015290    P0014252055        1
##       Price
## 54767   999
## 54768  2899
## 54769   253
## 54770   690
## 54771   245
## 54772  1493
# 找出價格的輪廓
head(purchase$Price)
## [1] 1069 1680  285  550  249 1780
max(purchase$Price,na.rm = TRUE)
## [1] 438888
min(purchase$Price,na.rm = TRUE)
## [1] 10
summary(purchase$Price,na.rm = TRUE)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##      10     599     899    2012    1680  438900      51

將資料保存到檔案中

data(iris)
View(iris)
write.csv(iris, 'iris.csv')
write.table(x = iris, file= 'iris.tab', sep='\t')

save(x = iris, file = 'iris.RData')
rm(iris)
load('iris.RData')

library(rpart)
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
fit <- rpart(Species ~., data = iris)
save(x = fit, file = 'fit.RData')
load('fit.RData')

讀取Excel 檔案

#install.packages('xlsx')
library(xlsx)

#download.file('https://raw.githubusercontent.com/ywchiu/rtibame/master/Data/FinancialReport.xlsx', destfile = 'FinancialReport.xlsx')

finrpt <- read.xlsx2("FinancialReport.xlsx", sheetIndex = 1, startRow = 1)

讀取半結構化資料 (JSON)

#下載JSON檔案
download.file('https://raw.githubusercontent.com/ywchiu/rtibame/master/Data/fb.json', destfile = 'fb.json')

#安裝與讀取jsonlite
#install.packages('jsonlite')
library(jsonlite)

#讀取JSON 檔案
json_data<- fromJSON('fb.json')
View(json_data$data)

讀取XML 資料

library(XML)
url <- 'http://download.post.gov.tw/post/download/county_h_10508.xml'
zipcode <- xmlToDataFrame(url)
names(zipcode) = c('郵遞區號', '中文名稱', '英文名稱')
head(zipcode)
##   郵遞區號     中文名稱                      英文名稱
## 1      100 臺北市中正區 Zhongzheng Dist., Taipei City
## 2      103 臺北市大同區     Datong Dist., Taipei City
## 3      104 臺北市中山區  Zhongshan Dist., Taipei City
## 4      105 臺北市松山區   Songshan Dist., Taipei City
## 5      106 臺北市大安區      Da’an Dist., Taipei City
## 6      108 臺北市萬華區     Wanhua Dist., Taipei City

開始蒐集網頁資料

library(rvest)
## Loading required package: xml2
## 
## Attaching package: 'rvest'
## The following object is masked from 'package:XML':
## 
##     xml
newsurl <- 'http://www.appledaily.com.tw/realtimenews/section/new/'
#?read_html
apple <- read_html(newsurl, encoding='UTF-8')
apple
## {xml_document}
## <html lang="zh-TW">
## [1] <head>\n  <meta charset="utf-8"/>\n  <title>蘋果即時新聞|蘋果日報|Apple Daily< ...
## [2] <body id="article" class="all">\n    <div class="wrapper">\n         ...
#as(apple, 'character')

DOM Tree

html_string <- '
<html> 
 <body> 
 <h1 id="title">Hello World</h1> 
 <a href="#" class="link">This is link1</a> 
 <a href="# link2" class="link">This is link2</a> 
 </body> 
</html>'
html_doc <- read_html(html_string)

# get h1
h1 <- html_nodes(html_doc, 'h1')
html_text(h1)
## [1] "Hello World"
# get a
a <- html_nodes(html_doc, 'a')
html_text(a)
## [1] "This is link1" "This is link2"
# get id=title, id -> #
title <- html_nodes(html_doc, '#title')
html_text(title)
## [1] "Hello World"
# get class=link, class -> .
link <- html_nodes(html_doc, '.link')
html_text(link)
## [1] "This is link1" "This is link2"
# get h1 in one line
html_text(html_nodes(read_html(html_string), 'h1'))
## [1] "Hello World"
# rewite with magrittr
html_string %>% read_html() %>% html_nodes('h1') %>% html_text()
## [1] "Hello World"
# magrittr example
tail(head(iris),3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
iris %>% head() %>% tail(3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

剖析頻果新聞

library(rvest)
newsurl <- 'http://www.appledaily.com.tw/realtimenews/section/new/'
apple <- read_html(newsurl, encoding='UTF-8')

# 原本的寫法
rtddt <- html_nodes(apple, '.rtddt a')
newslist = html_text(rtddt)
head(newslist)
## [1] "\n                                        16:27生活\n                                        家長轟教師罰學生抄書 1小時8千留言狂酸(0)\n                                    "         
## [2] "\n                                        16:26國際\n                                        香港首投族:要用選票趕走親中的建制派(14)\n                                    "          
## [3] "\n                                        16:24政治\n                                        【獨家】國民黨全代會窮到副主席認桌 發起...(45160)\n                                    "
## [4] "\n                                        16:22社會\n                                        被車子的音樂聲吸引 驚見駕駛燒炭身亡(98)\n                                    "          
## [5] "\n                                        16:18社會\n                                        攀水管爬3樓 白髮蜘蛛賊得手18萬(172)\n                                    "              
## [6] "\n                                        16:17生活\n                                        【台灣英文新聞】阿茲海默症有救了! 新藥...(196)\n                                    "
# Magrittr Version
#apple %>% html_nodes('li.rtddt') %>% html_text()
apple %>% html_nodes('.rtddt a') %>% html_text()
##  [1] "\n                                        16:27生活\n                                        家長轟教師罰學生抄書 1小時8千留言狂酸(0)\n                                    "         
##  [2] "\n                                        16:26國際\n                                        香港首投族:要用選票趕走親中的建制派(14)\n                                    "          
##  [3] "\n                                        16:24政治\n                                        【獨家】國民黨全代會窮到副主席認桌 發起...(45160)\n                                    "
##  [4] "\n                                        16:22社會\n                                        被車子的音樂聲吸引 驚見駕駛燒炭身亡(98)\n                                    "          
##  [5] "\n                                        16:18社會\n                                        攀水管爬3樓 白髮蜘蛛賊得手18萬(172)\n                                    "              
##  [6] "\n                                        16:17生活\n                                        【台灣英文新聞】阿茲海默症有救了! 新藥...(196)\n                                    "   
##  [7] "\n                                        16:16國際\n                                        Airbnb驚傳有屋主偷拍租客性愛  (291)\n                                    "              
##  [8] "\n                                        16:15政治\n                                        【更新】國民黨通過黨部主委直選 一年內實...(4239)\n                                    " 
##  [9] "\n                                        16:15社會\n                                        新北三峽山區車禍 1騎士卡車底命危待救(156)\n                                    "        
## [10] "\n                                        16:12社會\n                                        病樹路倒害命 騎士母親要求國賠(527)\n                                    "               
## [11] "\n                                        16:10財經\n                                        G20峰會沒邀請他 他的鬼影子卻縈繞不去(1211)\n                                    "       
## [12] "\n                                        16:10生活\n                                        幹部座車再遭潑紅土 樹黨譴責暴力(283)\n                                    "             
## [13] "\n                                        16:06財經\n                                        【省錢並非摳自己】她這樣做 3年還款40...(29424)\n                                    "   
## [14] "\n                                        16:04時尚\n                                        黛安克魯格撇情傷 Elie Saab薄紗...(505)\n                                    "           
## [15] "\n                                        16:03娛樂\n                                        【閨蜜狂喜】林熙蕾為舒淇開喝 林心如孕婦...(51333)\n                                    "
## [16] "\n                                        16:00社會\n                                        台化因空污遭罰10萬 告彰縣府敗訴(492)\n                                    "             
## [17] "\n                                        15:59財經\n                                        8月出口 學者料持平(146)\n                                    "                          
## [18] "\n                                        15:58體育\n                                        【更新】義大單局猛灌7分 12比3擊敗統...(6511)\n                                    "     
## [19] "\n                                        15:54國際\n                                         【不斷更新】香港立會選舉 投票率22%(1605)\n                                    "        
## [20] "\n                                        15:53國際\n                                        絕美Coser爆乳夾冰 網友揭其實她長這...(6885)\n                                    "      
## [21] "\n                                        15:53生活\n                                        讓紳士興奮的巨乳滑鼠墊 原來裡面是......(2416)\n                                    "    
## [22] "\n                                        15:49社會\n                                        大貨車自撞護欄 乘客破窗飛出命危(5463)\n                                    "            
## [23] "\n                                        15:46社會\n                                        父女吃冰搭捷運遭阻 嗆保全:不夠格去吃屎(35284)\n                                    "   
## [24] "\n                                        15:44社會\n                                        到喪家辦桌對撞機車 騎士飛落泥田亡(4883)\n                                    "          
## [25] "\n                                        15:44財經\n                                        天利盃宜蘭梅花湖鐵人三項今登場 4700...(302)\n                                    "      
## [26] "\n                                        15:43國際\n                                        <U+200B>高齡產婦「倫倫」 生下貓熊雙胞胎(844)\n                                    "     
## [27] "\n                                        15:41地產\n                                        不是教投機 他坦白房市多頭已逝(4048)\n                                    "              
## [28] "\n                                        15:40國際\n                                        大鵰未必好 讓「10倍男」告訴你(8776)\n                                    "              
## [29] "\n                                        15:34生活\n                                        布袋蓮佔滿金龍湖 居民憂生態危機(1538)\n                                    "            
## [30] "\n                                        15:32社會\n                                        【有片】汐止攔車砍人 3人中刀送醫(27400)\n                                    "

整理新聞資料

rtddt <-  apple %>% html_nodes('.rtddt a')
as(rtddt[1], 'character')
## [1] "<a href=\"/realtimenews/article/life/20160904/942193/家長轟教師罰學生抄書 1小時8千留言狂酸\" target=\"_blank\">\n                                        <time>16:27</time><h2>生活</h2>\n                                        <h1><font color=\"#ff0000\">家長轟教師罰學生抄書 1小時8千留言狂酸(0)</font></h1>\n                                    </a>"
title <- rtddt %>% html_nodes('h1') %>% html_text()

view_cnt <-  gsub( '(.+)\\((\\d+)\\)' , '\\2',    title)
view_cnt <- as.numeric(view_cnt)


category <- rtddt %>% html_nodes('h2') %>% html_text()

time <- rtddt %>% html_nodes('time') %>% html_text()
         
href <- rtddt %>% html_attr('href') 
url <- paste('http://www.appledaily.com.tw', href, sep='')

news <- data.frame(title, category, time, url,view_cnt) 
head(news)
##                                                title category  time
## 1          家長轟教師罰學生抄書 1小時8千留言狂酸(0)     生活 16:27
## 2           香港首投族:要用選票趕走親中的建制派(14)     國際 16:26
## 3 【獨家】國民黨全代會窮到副主席認桌 發起...(45160)     政治 16:24
## 4           被車子的音樂聲吸引 驚見駕駛燒炭身亡(98)     社會 16:22
## 5               攀水管爬3樓 白髮蜘蛛賊得手18萬(172)     社會 16:18
## 6    【台灣英文新聞】阿茲海默症有救了! 新藥...(196)     生活 16:17
##                                                                                                                           url
## 1               http://www.appledaily.com.tw/realtimenews/article/life/20160904/942193/家長轟教師罰學生抄書 1小時8千留言狂酸
## 2        http://www.appledaily.com.tw/realtimenews/article/international/20160904/942195/香港首投族:要用選票趕走親中的建制派
## 3 http://www.appledaily.com.tw/realtimenews/article/politics/20160904/941993/【獨家】國民黨全代會窮到副主席認桌 發起小額捐款
## 4                http://www.appledaily.com.tw/realtimenews/article/local/20160904/942189/被車子的音樂聲吸引 驚見駕駛燒炭身亡
## 5                     http://www.appledaily.com.tw/realtimenews/article/local/20160904/942084/攀水管爬3樓 白髮蜘蛛賊得手18萬
## 6 http://www.appledaily.com.tw/realtimenews/article/life/20160904/942194/【台灣英文新聞】阿茲海默症有救了!新藥可有效減緩症狀
##   view_cnt
## 1        0
## 2       14
## 3    45160
## 4       98
## 5      172
## 6      196
# Paste 範例
paste('hello', 'world')
## [1] "hello world"
paste('hello', 'world', sep = '')
## [1] "helloworld"

整理50頁新聞

newsdf <- data.frame()

for (page in 1:5){
  pageurl <- 'http://www.appledaily.com.tw/realtimenews/section/new/'
  newsurl <- paste(pageurl, page, sep='')
  print(newsurl)
  
  apple <- read_html(newsurl, encoding='UTF-8')
  rtddt <-  apple %>% html_nodes('.rtddt a')
  as(rtddt[1], 'character')
  title <- rtddt %>% html_nodes('h1') %>% html_text()
  
  view_cnt <-  gsub( '(.+)\\((\\d+)\\)' , '\\2',    title)
  view_cnt <- as.numeric(view_cnt)
  
  
  category <- rtddt %>% html_nodes('h2') %>% html_text()
  
  time <- rtddt %>% html_nodes('time') %>% html_text()
           
  href <- rtddt %>% html_attr('href') 
  url <- paste('http://www.appledaily.com.tw', href, sep='')
  
  news <- data.frame(title, category, time, url,view_cnt)
  newsdf <- rbind(newsdf, news)
}
## [1] "http://www.appledaily.com.tw/realtimenews/section/new/1"
## [1] "http://www.appledaily.com.tw/realtimenews/section/new/2"
## [1] "http://www.appledaily.com.tw/realtimenews/section/new/3"
## [1] "http://www.appledaily.com.tw/realtimenews/section/new/4"
## [1] "http://www.appledaily.com.tw/realtimenews/section/new/5"
head(newsdf[order(newsdf$view_cnt, decreasing = TRUE), ])
##                                                   title category  time
## 88  【獨家動畫】舒淇捷克出嫁淇媽哭花臉 私密...(392419)     娛樂 14:01
## 31  網美募款救浪貓挨轟斂財 「已委託律師處理...(174858)     生活 15:30
## 127 【各擁幸福】林若亞關島低調嫁孫志浩 賈靜...(158651)     娛樂 12:51
## 81            進擊的爸寶! 男騎車闖雪隧一路狂飆(78801)     社會 14:17
## 150           她希望姊姊永遠別回家 都是這個原因(60279)     生活 11:51
## 108                西班牙忠犬 苦守醫院6天等主人(59302)     國際 13:19
##                                                                                                                                      url
## 88  http://www.appledaily.com.tw/realtimenews/article/entertainment/20160904/941728/【獨家動畫】舒淇捷克出嫁淇媽哭花臉 私密婚禮只請20人
## 31                     http://www.appledaily.com.tw/realtimenews/article/life/20160904/941919/網美募款救浪貓挨轟斂財 「已委託律師處理」
## 127       http://www.appledaily.com.tw/realtimenews/article/entertainment/20160904/941937/【各擁幸福】林若亞關島低調嫁孫志浩 賈靜雯賀喜
## 81                            http://www.appledaily.com.tw/realtimenews/article/local/20160904/941975/進擊的爸寶! 男騎車闖雪隧一路狂飆
## 150                            http://www.appledaily.com.tw/realtimenews/article/life/20160904/942045/她希望姊姊永遠別回家 都是這個原因
## 108                        http://www.appledaily.com.tw/realtimenews/article/international/20160904/941966/西班牙忠犬 苦守醫院6天等主人
##     view_cnt
## 88    392419
## 31    174858
## 127   158651
## 81     78801
## 150    60279
## 108    59302
write.csv(x= newsdf, file = 'news.csv')