R 語言上手篇

Wush Wu

2015年9月25日

目錄

R 來自世界上最專業的統計學家

取自 http://myfootpath.com/careers/engineering-careers/statistician-careers/

R 可以輸出高品質的視覺化

取自 http://www.r-bloggers.com/mapping-the-worlds-biggest-airlines/

R 有驚人彈性和潛力

取自 http://r4stats.com/2013/03/19/r-2012-growth-exceeds-sas-all-time-total/

R 很容易和其他工具整合

R 很容易擴充和客製化

取自 http://img.diynetwork.com/DIY/2003/09/18/t134_3ca_med.jpg

和其他工具相比,R 的特色

範例 - 探索數據的分佈

範例 - 探索數據的分佈

shapiro.test(x)

    Shapiro-Wilk normality test

data:  x
W = 0.94356, p-value = 0.0003198

範例 - 探索數據的分佈

x1 <- rnorm(50)
x2 <- rt(50, df = 2)
plot(density(x1), xlim = range(c(x1, x2)), main = "Sample PDF")
lines(density(x2), col = 2)
legend("topright", c("x1", "x2"), lty = 1, col = 1:2)

範例 - 探索數據的分佈

ks.test(x1, x2)

    Two-sample Kolmogorov-Smirnov test

data:  x1 and x2
D = 0.24, p-value = 0.1124
alternative hypothesis: two-sided

範例 - 數據間的比較

範例 - 數據間的比較

# 假設方法A 真正的轉換率和就是 3 / 5000
p <- 3/5000
# 我們可以模擬1000次在10000個點擊下,方法A 的轉換數
plot(density(x <- rbinom(1000, 10000, p)))

範例 - 數據間的比較

# 估計超過我們觀測值的機率
mean(x > 10)
[1] 0.042

範例 - 數據間的比較

library(binom)
binom.confint(c(10, 3), c(10000, 5000), methods = "exact")
  method  x     n  mean        lower       upper
1  exact 10 10000 1e-03 0.0004796397 0.001838264
2  exact  3  5000 6e-04 0.0001237515 0.001752444

範例 - 數據間的比較

範例 - 相關性

範例 - 相關性

範例 - 相關性

範例 - 經濟學人風格的視覺化

R 不只有傳統的資料分析

收集數據

收集數據 – Google Spreadsheet

特定領域 – 股票分析

library(quantmod)
getSymbols("^TWII")
    As of 0.4-0, 'getSymbols' uses env=parent.frame() and
 auto.assign=TRUE by default.

 This  behavior  will be  phased out in 0.5-0  when the call  will
 default to use auto.assign=FALSE. getOption("getSymbols.env") and 
 getOptions("getSymbols.auto.assign") are now checked for alternate defaults

 This message is shown once per session and may be disabled by setting 
 options("getSymbols.warning4.0"=FALSE). See ?getSymbols for more details.
[1] "TWII"
head(TWII)
           TWII.Open TWII.High TWII.Low TWII.Close TWII.Volume
2007-01-02   7871.41   7937.26  7843.60    7920.80     5710600
2007-01-03   7954.96   7999.42  7917.30    7917.30     5951400
2007-01-04   7929.89   7955.90  7901.24    7934.51     5717400
2007-01-05   7940.20   7942.23  7821.71    7835.57     5181400
2007-01-08   7778.57   7797.57  7736.11    7736.71     4292400
2007-01-09   7778.38   7827.93  7778.38    7790.01     4516000
           TWII.Adjusted
2007-01-02       7920.80
2007-01-03       7917.30
2007-01-04       7934.51
2007-01-05       7835.57
2007-01-08       7736.71
2007-01-09       7790.01

特定領域 - 股票分析

chartSeries(TWII, subset = "last 4 months", TA = c(addVo(), addBBands()))

特定領域 - 棒球分析

library(Lahman)
head(Teams[,c("yearID", "name", "Rank", "W", "L", "R", "RA")])
  yearID                    name Rank  W  L   R  RA
1   1871    Boston Red Stockings    3 20 10 401 303
2   1871 Chicago White Stockings    2 19  9 302 241
3   1871  Cleveland Forest Citys    8 10 19 249 341
4   1871    Fort Wayne Kekiongas    7  7 12 137 243
5   1871        New York Mutuals    5 16 17 302 313
6   1871  Philadelphia Athletics    1 21  7 376 266

特定領域 - 棒球分析

totalRS <- Teams %>% select(yearID, R, G) %>% 
  mutate(AvgRperG = R/G) %>% group_by(yearID) %>% summarise(sum(AvgRperG))
names(totalRS) <- c("yearID", "RUN")
ggplot(data = totalRS, aes(x = yearID, y = RUN)) + stat_smooth() + geom_line()
geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.

特定領域 - 棒球分析

head(filter(Pitching, playerID == "wangch01") %>% select(playerID, yearID, W, L, ERA))
  playerID yearID  W L  ERA
1 wangch01   2005  8 5 4.02
2 wangch01   2006 19 6 3.63
3 wangch01   2007 19 7 3.70
4 wangch01   2008  8 2 4.07
5 wangch01   2009  1 6 9.64
6 wangch01   2011  4 3 4.04

特定領域 - 文字探勘

suppressPackageStartupMessages({
  library(jiebaR)      # 斷詞利器
  library(tm)          # 文字詞彙矩陣運算
  library(slam)        # 稀疏矩陣運算
  library(wordcloud)   # 文字雲
  library(topicmodels) # 主題模型
  library(igraph)      # 主題模型關聯
})

特定領域 - 資料科學愛好者年會講者資料分析

[1] 27
Warning in split.default(., rep(1:15, each = 30)): data length is not a
multiple of split variable
陳昇瑋 Sheng-Wei Chen 年會總召, 中央研究院
資訊科學研究所/ 研究員 陳昇瑋博士目前為中央研究院資訊科學
研究所研究員,同時是多媒體網路與系統實驗室主持人。他的研究焦
點著重在使用者滿意度、多媒體系統、社群計算及計算社會學等領域
,在多媒體系統及使用者經驗的量測及管理方面持續有代表性的研究
創見。  陳博士堅信資料及資料分析的價值,長期推廣資料科學及
其在各領域的應用,除本身研究皆基於資料來解決實際生活中的問題
,2014 年開始主辦「台灣資料科學愛好者年會」,期能將對於
資料科學的熱情傳達給大眾,一起來探索資料科學的潛力,將資料科
學引入每個人的專業領域之中。他十分期待能夠讓資料分析在台灣不
再是口號,而是大家手邊隨時可用來解決問題及創造價值的工具。 
 欲瞭解陳博士的研究及心得分享,請至他的個人網頁一探究竟。 
 

特定領域 - 資料科學愛好者年會講者資料分析

Warning in split.default(., rep(1:15, each = 30)): data length is not a
multiple of split variable
陳 昇 瑋 Sheng Wei Chen 年會 總召 中央研
究院 資訊 科學 研究所 研究員 陳 昇 瑋 博士 目前 為
 中央研究院 資訊 科學 研究所 研究員 同時 多媒體 網路
 系統 實驗室 主持人 他 研究 焦點 著重 使用者 滿意度
 多媒體系統 社群 計算 計算 社會學 領域 多媒體系統 使
用者 經驗 量 測及 管理方面 持續 有 代表性 研究 創見
 陳博士 堅信 資料 資料 分析 價值 長期 推廣 資料 科
學 及其 各 領域 應用 除 本身 研究 皆 基於 資料 來
 解決 實際 生活 中 問題 2014 年 開始 主辦 台 
灣 資料 科學 愛好者 年會 期能將 對於 資料 科學 熱情
 傳達 給大眾 一 起來 探索 資料 科學 潛力 將 資料 
科學 引入 每個 人 專業 領域 之中 他 十分 期待 能夠
 讓 資料 分析 台灣 不再 口號 而是 大家 手邊 隨時 
可 用來 解決問題 創造 價值 工具 欲瞭解 陳博士 研究 
心得 分享 請 至 他 個人 網頁 一探 究竟

特定領域 - 資料科學愛好者年會講者資料分析

特定領域:互動式網頁服務

特定領域:API Server

大規模的數據分析

R 的Community

Hadley近年來對R 的影響

package downloads
1 Rcpp 208576
2 ggplot2 180109
3 stringr 168141
4 stringi 167537
5 plyr 166113
6 digest 156862
7 magrittr 156195
8 scales 152361
9 reshape2 147689
10 RColorBrewer 138724

台灣的本土R 社群

R 的環境設定

安裝R

安裝R

安裝R

sudo sh -c 'echo "deb http://cran.csie.ntu.edu.tw/bin/linux/ubuntu trusty/" >> /etc/apt/sources.list'
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E084DAB9
sudo apt-get update && apt-get install -y r-base libcurl4-openssl-dev libxml2-dev

安裝Rstudio

Rstudio 環境說明

熟悉RStudio的 命令列 界面

熟悉RStudio的 程式碼編輯 界面

熟悉RStudio的其他頁面

R 的套件系統

安裝R 的套件

安裝swirl

# 在命令列輸入:
install.packages('swirl', repos = 'http://taiwanrusergroup.github.io/R')

載入swirl

library(swirl)

進入swirl 界面

swirl() # 括號很重要

手動安裝swirl 課程

install_course_github("wush978", "DataScienceAndR", "course")

再次進入swirl,並進入DataScienceAndR

swirl 疑難排解

作業說明

繳交作業的格式

d01921016/
d01921016/RBasic-02-HW.R
d01921016/RBasic-03-HW.R
d01921016/RBasic-04-HW.R
d01921016/RBasic-05-HW.R
d01921016/RBasic-06-HW.R
d01921016/RBasic-07-HW.R

這份教材是最近寫出來的…

Q&A

R vs Python