Mais conteúdo relacionado Semelhante a 給軟體工程師的不廢話 R 語言精要班 (20) 給軟體工程師的不廢話 R 語言精要班1. 在開始之前
(1) 請到 https://cran.r-project.org/ 下載最新版的 R
(2) 請到
https://www.rstudio.com/products/rstudio/download/
下載 open source liscence 的 RStudio Desktop
(3) 請到 http://datascienceandr.org 依照指示下載最新版課
程
(4) 技術問題可以參閱
https://github.com/wush978/DataScienceAndR/wiki 或至
https://gitter.im/wush978/DataScienceAndR 詢問
(5) 這兩天的上課講義在 http://tinyurl.com/dl-r4swe
1
8. R 與 Python
Syntax Python R
library from math import * library(tree)
assignment =, +=, -=, *=, /=, %= =, <-, <<-, ->
basic
data type
int, long, float,
bool, str, etc.
Integer, numeric,
logical, character, etc.
(all vectorized)
complex
data type
list, iterator, set,
dict
list, matrix, data.frame
for statement for i in range(10): for(i in 1:10)
function
definition
def myfunc(): myfunc = function(){…}
arithmetic
operators
+, -, *, /, %
+, -, *, /, %/%, %%,
matrix algebra operators
取自淡江統計陳景祥老師部落格 http://steve-chen.tw/?p=4498
9. R 與 Python (cont.)
取自 DSP 謝宗震博士部落格 http://readata.org/r-vs-python/
9
13. 精簡的 R (cont.)
▪ 一行程式碼進行統計檢定
> shapiro.test(rnorm(100))
Shapiro-Wilk normality test
data: rnorm(100)
W = 0.98889, p-value = 0.5762
> shapiro.test(iris$Petal.Length)
Shapiro-Wilk normality test data:
iris$Petal.Length
W = 0.87627, p-value = 7.412e-10
13
14. 精簡的 R (cont.)
▪ 三行程式碼進行線性回歸
> sample <- read.csv(“sampleData.csv")
> model <- lm(value~., data=sample)
> summary(model)
14
15. 範例 – A/B Testing (常見於電子商
務)
▪ 假如電子商務網站設計了兩種推薦方法
▪ 現在想要比較兩種方法的成果
▪ 方法 A: 在 10000 次點擊中,有 10 個購買
▪ 方法 B: 在 5000 次點擊中,有 3 個購買
▪ 如何知道這兩種方法的轉換率 (購買/點擊)
是否明顯不同?
15
16. 範例 - A/B Testing (成效比較)
▪ 統計檢定的概念
▪ 如果方法 A 的轉換率與方法 B 相同 (3/5000)
▪ 那在 10000 點擊中,發生 10 個以上購買的機率是多少?
> p <- 3/5000
> plot(density(x <- rbinom(1000, 10000, p)))
> abline(v=10, col=2)
> mean(x > 10)
[1] 0.036
16
17. 範例 – A/B Testing (信賴區間)
▪ 想看信賴區間?透過套件,一行就可以獲
得結果
▪ 還有許多其他方法可以嘗試
> install.packages(“binom”)
> 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
17
19. 資料蒐集 - R Crawler
▪ httr, html2, rvest, etc.
▪ 參考 Chih-Cheng Liang 在 2015 台灣資料科
學愛好者年會上的 Talk
▪ http://chihchengliang.github.io/DSC2015_C
rawler/
19
20. 資料整理
▪ 介接各式資料源與資料格式
▪ https://cran.r-project.org/doc/manuals/r-release/R-
data.html
▪ 核心函數所提供的資料整理函式庫
▪ 字串: gsub,regmatch,substring, paste,...
▪ 型別轉換: as.numeric,as.character,…
▪ 類別化: cut,factor,...
▪ 泛用: split,...
▪ 社群開發的強力套件
▪ 字串: stringr,stringi
▪ 時間: lubridate
▪ 資料整理與整合: dplyr
20
26. 眾多的套件 – 串接線上服務
▪ Google Spread Sheets R API
▪ https://github.com/jennybc/googlesheets
▪ RgoogleMaps
▪ https://cran.r-project.org/web/packages/RgoogleMaps/
▪ readxl (整合 Excel)
▪ https://cran.r-project.org/web/packages/readxl/
▪ foreign (整合 Minitab, S, SAS, SPSS, etc.)
▪ https://cran.r-project.org/web/packages/foreign/
▪ DBI (R Database Interface)
▪ https://cran.r-project.org/web/packages/DBI/index.html
26
27. 眾多的套件 - 股票分析
> install.packages("quantmod")
> library(quantmod)
> getSymbols("^TWII")
[1] "TWII"
> head(TWII)
TWII.Open TWII.High TWII.Low TWII.Close TWII.Volume TWII.Adjusted
2007-01-02 7871.41 7937.26 7843.60 7920.80 5710600 7920.80
2007-01-03 7954.96 7999.42 7917.30 7917.30 5951400 7917.30
2007-01-04 7929.89 7955.90 7901.24 7934.51 5717400 7934.51
2007-01-05 7940.20 7942.23 7821.71 7835.57 5181400 7835.57
2007-01-08 7778.57 7797.57 7736.11 7736.71 4292400 7736.71
2007-01-09 7778.38 7827.93 7778.38 7790.01 4516000 7790.01
27
29. 眾多的套件 - 棒球分析
> 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
29
32. 眾多的套件 - 文字探勘
> suppressPackageStartupMessages({
+ library(jiebaR) # 斷詞利器
+ library(tm) # 文字詞彙矩陣運算
+ library(slam) # 稀疏矩陣運算
+ library(wordcloud) # 文字雲
+ library(topicmodels) # 主題模型
+ library(igraph) # 主題模型關聯
+ })
32
*取自 R 社群 2014 閃電秀 by George Chao
33. 文字探勘 – 斷詞
▪ 陳 瑋 Sheng Wei Chen 年會 總召 中央研究院
▪資訊 科學 研究所 研究員 陳 瑋 博士 目前 為 中央研究院 資訊 科學 研究
所 研究員 同時 多媒體 網路 系統 實驗室 主持人 他 研究 焦點 著重 使用
者 滿意度 多媒體 系統 社群 計算 計算 社會學 領域 多媒體系統 使用者
經 驗 量 測及 管理方面 持續 代表性 研究 創見 陳博士 堅 信 資料 資料 分
析 價值 長期 推廣 資料 科學 及其 各 領域 應用 除 本身 研究 皆 基於 資
料 來 解決 實際 生活 中 問題 2014 年 開始 主辦 台 灣 資料 科 學 愛好者
年會 期能將 對於 資料 科學 熱情 傳達 給大 眾 一 起來 探索 資料 科學 潛
力 將 資料 科學 引入 每個 人 專業 領域 之中 他 十分 期待 能夠 讓 資料
分析 台灣 不再 口號 而是 大家 手邊 隨時 用來 解決問 題 創造 價值 工具
欲瞭解 陳博士 研究 心得 分享 請 至 他 個人 網頁 一探 究竟
33
*取自 R 社群 2014 閃電秀 by George Chao
35. 眾多的套件 - 互動式網頁
▪ Shiny: A web application framework for R
▪ K-Means Example
▪ http://shiny.rstudio.com/gallery/kmeans-
example.html
35
37. 用 R 語言翻轉教室學 R
▪ 學什麼?
▪ 基本使用知識
▪ 讀取資料與讀取中文
▪ 從公開資料中萃取資訊
▪ 用 R 整理資訊
▪ 用 R 將整理好的資訊繪製統計圖表與地圖
▪ 怎麼學?
▪ 用 R 學 R
37
39. 安裝 R
▪ 請至 http://cran.csie.ntu.edu.tw/ 下載 3.2 版以上的 R
▪ For Windows Users
▪ https://www.youtube.com/watch?v=FsOHPGUIDZU
▪ 注意影片下載的是 3.0.2版,請安裝最新版 (3.2版以上)
▪ For Mac Users
▪ https://www.youtube.com/watch?v=72MYRBNo5Bk
▪ 感謝中華 R 軟體學會的李明昌老師提供影片
▪ For Ubuntu Users
▪ 請參照下列說明
▪ http://cran.csie.ntu.edu.tw/bin/linux/ubuntu/README.html
39
40. 安裝 R Studio
▪ R Studio 為 R 的 IDE 環境
▪ 圖形化介面,完整支援 R 的編輯、繪圖以及文件說明
▪ 具備「自動完成」功能
▪ 在 Windows 下支援 UTF-8 的檔案編碼
▪ 請到 R Studio 官方網站
https://www.rstudio.com/products/RStudio/
▪ 下載並安裝 R Studio Desktop Open Source
Edition
40
42. 讓我們從命令列開始
▪ R 是一種 script language,使用者可以藉由命令列
執行指令
▪ R 的提示符號 >
> "hello world"
[1] "hello world"
> 1
[1] 1
> 1+1
[1] 2
> 1+
+ 1
[1] 2
提示符號變成 + 表示指令未完成
字串
數字
數字運算
42
43. 更多命令
> a <- 1
> a
[1] 1
> a + 1
[1] 2
> a = a + 1
[1] 2
> a + 1 -> b
> b
[1] 3
> c(a, b, 1, 11, 21)
[1] 2 3 1 11 21
> 1:5
[1] 1 2 3 4 5
串接數值
賦值 (assignment)
觀察其他資訊區 Environment
分頁下的變化
43
44. 更多命令 (cont.)
> me
Error: object 'me' not found
試試看鍵入 me 之後,不要按 Enter 改按 Tab
試試看鍵入 me 之後,按 Ctrl + C 或 ESC
> "1" + "1"
Error in "1" + "1" : non-numeric argument to
binary operator
試試看鍵入 ?me 之後,按 tab 然後 Enter,看看檔案
系統區出現了什麼
44
45. 使用編輯介面
▪ 左上角選單 File -> New File -> R Script
▪ 在編輯區
▪ 鍵入 1 + 1 按下 Ctrl + Enter,觀察命令列區
▪ 鍵入 1/2 按下 Enter
▪ 鍵入 2*2 按下 Ctrl + Alt + B,觀察命令列區
▪ Tab 鍵在編輯介面下一樣可用
▪ 養成在編輯介面寫程式的習慣
45
47. 安裝與使用 R 套件
▪ 利用 R Studio 安裝與載入
▪ 檔案系統區 > Packages 分頁
▪ 使用命令列安裝套件
> install.packages("套件名稱", repos = "套件庫網址)
▪ 使用命令列載入套件
> library(套件名稱)
47
48. 安裝用來學習 R 的 R 套件 - swirl
▪ 請在命令列執行下列指令以安裝互動課程所
需的套件
▪ 請在命令列執行下列指令以載入並啟動課程
> source("http://wush978.github.io/R/init-swirl.R")
> library(swirl)
> swirl()
48
52. 互動式學習環境 (cont.)
▪ RBasic: 講解 R 的基礎知識與語法
▪ RDataEngineer: 講解載入資料至 R 環境,
以及清理、整理資料的作法
▪ RVisualization: 講解利用 R 視覺化資料的
知識
▪ RProgramming: 介紹 R 的程式功能
52
53. 本次課程的學習路徑
▪ R 語言入門
▪ RBasic-01~06
▪ R 語言視覺化基礎
▪ RVisualization-01~02
▪ R 語言資料工程
▪ Rbasic-07
▪ RDataEngineer-01, 05, 06
▪ R 語言視覺化進階
▪ RVisualization-03, 04
53
54. Let’s Do It
▪ 實際操作 swirl 課程,請各位同學進行
▪ Hello-DataScienceAndR
▪ RBasic-01-Introduction
▪ 如有任何問題,如亂碼、不知該如何進行,
請舉手向助教或講師洽詢
54
57. 名目資料 (Nominal)
▪ Name
▪ 畢業學校:交大、台大、清大……
▪ 車輛廠牌:Toyota, VW, Benz
▪ 分類
▪ 性別:男、女、其他
▪ 產業:金融、資訊、製造……
▪ 屬性上的有無
▪ 年收入>100萬:是、否
▪ 資料的先後、順序沒有意義
57
59. 順序資料 (Ordinal)
▪ 先後的意義
▪ 硬度表
(1) 滑石, (2) 石膏, (3) 方解石, (4) 螢石, (5) 磷灰石,
(6) 正長石, (7) 石英, (8) 黃玉, (9) 剛玉, (10) 金剛石
▪ CPBL 戰績排名
(1) Lamigo (2) 中信 (3) 義大 (4) 統一……
▪ 有序的名目資料
▪ 不確定間隔的意義
59
60. 區間資料 (Interval)
▪ 溫度
▪ 攝氏溫標: 0⁰C, 100⁰C
▪ 時間
▪ 秒、分、時、日、年
▪ 各式度量衡
▪ 長度:公尺、公寸、英尺、英吋
▪ 重量:公斤、磅
▪ 具有固定間隔的順序資料
60
63. R 的基本資料型態
▪ 邏輯資料 (logical)
▪ TRUE, FALSE, T, F
▪ 整數資料 (integer)
▪ …, -1, -2, 0, 1, 2, …
▪ 皆以長整數 (Long) 儲存
▪ 數值資料 (numeric):
▪ …, -1.0, -0.5, 0.0, 3.33333…, 2.0, pi
▪ 皆以雙精數 (Double) 儲存
▪ 字串資料 (character):
▪ 'a', "abc", "Wush Wu", "許懷中"
63
66. R 的向量化資料型態
<= 相當於 a + c(1, 1, 1, 1, 1)
<= 每個元素都各別乘 2
> a <- c(1,2,3,4,5)
> a
[1] 1 2 3 4 5
> a+1
[1] 2 3 4 5 6
> a*2
[1] 2 4 6 8 10
67
67. R 的基本資料型態
▪ 邏輯向量 (logical)
▪ 整數向量 (integer)
▪ 數值向量 (numeric):
▪ 字串向量 (character):
68
68. 邏輯向量 (logical)
▪ 用於作布林 (boolean) 運算,流程控制
> c(T, F, TRUE, FALSE)
[1] TRUE FALSE TRUE FALSE
> a = -1
> ifelse(a > 0, 1, 0)
[1] 0
> a > 0
[1] FALSE
69
70. 數值向量
▪ 每個數值大小 8 bytes (雙精確浮點數)
> c(1.0, .1, 1e-2, 1e2, 1.2e2)
[1] 1.00 0.10 0.01 100.00 120.00
71
71. 字串向量
▪ NULL 結尾的字串向量
> c("1","a","中文")
[1] "1" "a" "中文"
> c("a0b")
Error: nul character not allowed (line 1)
72
73. R 物件可以很複雜
▪ 複雜的 R 物件都是由基礎的 R 物件所組成
> g <- lm(dist ~ speed, cars)
> str(head(g))
List of 6
$ coefficients : Named num [1:2] -17.58 3.93
..- attr(*, "names")= chr [1:2] "(Intercept)" "speed"
$ residuals : Named num [1:50] 3.85 11.85 -5.95 12.05 2.12 ...
..- attr(*, "names")= chr [1:50] "1" "2" "3" "4" ...
$ effects : Named num [1:50] -303.914 145.552 -8.115 9.885 0.194 ...
..- attr(*, "names")= chr [1:50] "(Intercept)" "speed" "" "" ...
$ rank : int 2 $ fitted.values: Named num [1:50] -1.85 -1.85 9.95 9.95 13.88 ...
..- attr(*, "names")= chr [1:50] "1" "2" "3" "4" ...
$ assign : int [1:2] 0 1
74
74. Let’s do it!
▪ 實際操作 R 的基礎資料型態
▪ RBasic-02-Data-Structure-Vectors
▪ RBasic-03-Data-Structure-Object
75
75. 習題題解
year1 <- 87:91
# 社會服務業自民國87至民國91年的年度用電量(度)
power1 <- c(6097059332, 6425887925, 6982579022, 7323992602.53436, 7954239517)
# 製造業自民國87至民國91年的年度用電量(度)
power2 <- c(59090445718, 61981666330, 67378329131, 66127460204.6482,
69696372914.6949)
year1 power1 power2
87 6097059332 59090445718
88 6425887925 61981666330
89 6982579022 67378329131
90 7323992602.53436 66127460204.6482
91 7954239517 69696372914.6949
76
76. 習題題解 (cont.)
year1 power1 power2
87 6097059332 59090445718
88 6425887925 61981666330
89 6982579022 67378329131
90 7323992602.53436 66127460204.6482
91 7954239517 69696372914.6949
找出社會服務業用電量超過7x109 的年份
軟體工程師的想法:
(1) 找出 power1 陣列大於 7x109 的 index
(2) 取出 year1 相同 index 的值
> index = which(power1 > 7e9)
> year1[index]
[1] 90 91
用 R 怎麼做?
欸,老師你沒教!
77
77. 習題題解 (cont.)
year1 power1 power2
87 6097059332 59090445718
88 6425887925 61981666330
89 6982579022 67378329131
90 7323992602.53436 66127460204.6482
91 7954239517 69696372914.6949
找出社會服務業用電量超過 7x109 的年份
R 語言的思維
(1) 年份跟用電量是互相對應的
(2) 那就取出社會服務業用電量超過 7x109 的年份吧
> year1[power1 > 7e9]
[1] 90 91
78
78. 習題題解 (cont.)
> power1 > 7e9
[1] FALSE FALSE FALSE TRUE TRUE
> year1
[1] 87 88 89 90 91
> year1[power1 > 7e9]
[1] 90 91
79
79. 習題題解 (cont.)
> pca <- prcomp(USArrests, scale = TRUE)
> str(pca)
List of 5
$ sdev : num [1:4] 1.575 0.995 0.597 0.416
$ rotation: num [1:4, 1:4] -0.536 -0.583 -0.278 -0.543 0.418 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
.. ..$ : chr [1:4] "PC1" "PC2" "PC3" "PC4"
$ center : Named num [1:4] 7.79 170.76 65.54 21.23
..- attr(*, "names")= chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
$ scale : Named num [1:4] 4.36 83.34 14.47 9.37
..- attr(*, "names")= chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
$ x : num [1:50, 1:4] -0.976 -1.931 -1.745 0.14 -2.499 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:50] "Alabama" "Alaska" "Arizona" "Arkansas" ...
.. ..$ : chr [1:4] "PC1" "PC2" "PC3" "PC4" - attr(*, "class")= chr
"prcomp“
> pca$sdev
[1] 1.575 0.995 0.597 0.416
> pca$[["sdev“]]
[1] 1.575 0.995 0.597 0.416
80
81. factor?
▪ 內建的 factor 範例
> head(CO2$Type)
[1] Quebec Quebec Quebec Quebec Quebec Quebec
Levels: Quebec Mississippi
82
82. 看似字串,其實不然
> dput(CO2$Type)
structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label =
c("Quebec", "Mississippi" ), class = "factor")
83
86. R 的 Matrix
> x <- matrix(1:4, 2, 2)
> x
[,1] [,2]
[1,] 1 3
[2,] 2 4
> class(x)
[1] "matrix
> attributes(x)
$dim
[1] 2 2
87
89. R 的 Array 與 Attributes
> x <- 1:8
> x
[1] 1 2 3 4 5 6 7 8
> attr(x, "dim") <- c(2, 2, 2)
> x
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
90
91. Let’s do it
▪ 實際操作 R 的 Matrix 以及 Array
▪ 請同學們完成 RBasic-05-Arrays-Matrices
92
92. 習題題解
▪ 𝑦 = 𝑋 ∙ 𝛽 為什麼不直接 solve(y, X) 求 𝛽?
▪ 請 ?solve 會發現第一個參數必須是方陣
▪ R 語言有可以求解非方陣矩陣相乘的函式嘛?
▪ 𝛽 = (𝑋 𝑇
∙ 𝑋)−1
∙ 𝑋 𝑇
∙y
> beta.hat <- solve(t(X) %*% X) %*% t(X) %*% y
▪ (𝑋 𝑇
∙ 𝑋)𝛽 = 𝑋 𝑇
∙y
> beta.hat <- solve((t(X) %*% X), t(X) %*% y)
93
94. 基本資料型態的向量必須是同質的
> x <- 1:10
> class(x)
[1] "integer"
> x
[1] 1 2 3 4 5 6 7 8 9 10
> x[1] <- "1"
> class(x)
[1] "character"
> x
[1] "1" "2" "3" "4" "5" "6" "7"
[8] "8" "9" "10"
牽一髮而動全身
95
97. > x <- list(1:5, c("a","b"))
> x
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] "a" "b"
list
98
100. list & names
> x <- list(1:5, c("a", "b"))
> x
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] "a" "b"
> attributes(x)
NULL
101
101. > x <- list(a = 1:5, b = c("a", "b"))
> x
$a
[1] 1 2 3 4 5
$b
[1] "a" "b"
> attributes(x)
$names
[1] "a" "b"
102
list & names (cont.)
102. $
> x <- list(a = 1:5, b = c("a", "b"))
> x$a
[1] 1 2 3 4 5
> x$b
[1] "a" "b"
103
103. 從 list 到 data.frame
▪ list 提供了處理異質資料的工具
▪ R 的物件導向系統就是以 list 為基礎
▪ 將 list 用於結構化資料仍然不甚直覺
▪ 不像矩陣提供許多方便的 API
▪ 所以我們有了 data.frame
▪ 用於結構化資料的 R 物件
▪ 兼具 list 與 matrix 的特性
104
105. R 的 Data Frame
▪ 結構化資料的典範
The main driver for Distributed DataFrame is to have a
cluster-based, big data representation that’s friendly to the
RDBMSs and data science community. Specifically we
leverage SQL’s table and R’s data.frame concepts, taking
advantage of 30 years of SQL development and R’s
accumulated data science wisdom.
▪ Source: http://ddf.io/design.html
106
106. 看看 Data Frame 長甚模樣
> 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
107
107. Data Frame 是一種 List
> class(iris)
[1] "data.frame"
> is.list(iris)
[1] TRUE
> head(iris[[1]])
[1] 5.1 4.9 4.7 4.6 5.0 5.4
108
108. 但又可以當作 Matrix 來存取
> iris[1,]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
> iris[1,1]
[1] 5.1
不同之處在於,matrix 中所有資料型態必須一致,
但 data.frame 由於具備 list 的特性,可以容許各
column 的資料型態不同
109
109. Let’s do it
▪ 實際操作 R 的 List 以及 Data Frame
▪ 請同學們完成 RBasic-06-List-DataFrame
110
110. 習題題解
這個 𝑦 = 𝑋 ∙ 𝛽 到底是在搞什麼?
matrix 與 data.frame 兩章的習題,讓同
學體驗了現今資料科學最常用的一種技法 –
統計建模
111
112. 習題題解 (cont.)
▪ 真實的 y 其實不可知,因為測量總是有誤差,
▪ 測量值與真實值之間的差距叫 error
▪ 模型的預測值與測量值之間的差距叫
residual (殘差)
113
117. 方程式介面
▪ y ~ x1 + x2 + x3: 描述 y 與 X 的關係
▪ data: 描述 y, x1, x2, x3
▪ …: 代表演算法的參數
▪ data2: 測試資料集
▪ 方程式介面支援各種 operator: +-:*|^Il
▪ http://faculty.chicagobooth.edu/richard.hahn
/teaching/FormulaNotation.pdf
> g <- lm(y~ x1 + x2 + x3, data, …)
> predict(g, data2)
118
124. 字串向量的記憶體用量較難估計
> speaker <- readLines("speaker.txt")
> speaker[2]
[1] "年會總召, 中央研究院資訊科學研究所/ 研究員"
> length(speaker)
[1] 216
> file.size("speaker.txt")
[1] 18464
> object.size(speaker)
24664 bytes
125
128. Pass by Value
▪ 傳入函式中的參數
▪ 會 copy 一份副本在函式中使用
▪ 在函式中的修改,不會影響到原本傳入參數在
外部的值
129
130. tracemem
> x<-c(1,2,3)
> tracemem(x)
[1] "<000000001C45EA30>"
> x <- c(1,2,3)
> tracemem(x)
[1] "<0000000017ED9AD0>"
> y <- x
> tracemem(y)
[1] "<0000000017ED9AD0>"
> y[2] <- 3
tracemem[0x0000000017ed9ad0 -> 0x0000000017f6f888]:
131
132. R 的繪圖引擎
X11
Unix 作業系統的 X-Window GUI
Windows
用於 Windows 作業系統
Quartz
MAC OS X 系統
Postscript
用於印表機或是建立 PS 文件
pdf, png, jpeg
用於建立特定格式的檔案
html 與 javascript
用於建立網頁上的互動式圖表
133
133. R的基本繪圖 API
▪ 高階繪圖指令
▪ 依據輸入的資料產生完整的圖形
▪ plot, pie, hist, boxplot, barplot, …
▪ 清空先前繪圖結果
▪ 低階繪圖指令
▪ 修飾、裝飾當前的圖形
▪ lines, points, legend, text,
polygon, …
▪ 繪圖引擎參數控制
▪ par
134
134. 基本繪圖 API 的精神
▪ 以直角座標系統繪製各種幾何圖形
▪ 與模型相結合,依據模型的型態繪製結果
plot.lm, rpart::plot.rpart
135
137. 連續型變數
> par(mfrow = c(1,2))
> plot(density(iris$Sepal.Length))
> hist(iris$Sepal.Length)
138
138. > d1 <- sample(1:6, 100, replace=TRUE)
> hist(d1)
139
139. > d1 <- sample(1:6, 100, replace=TRUE)
> d1 <- sample(1:6, 100, replace=TRUE)
> hist(d1+d2)
140
141. > d1 <- sample(1:6, 10000, replace=TRUE)
> hist(d1)
142
143. 類別 vs. 類別
> data(Titanic)
> mosaicplot(~Sex + Survived, data = Titanic,
+ main = "Survival on The Titanic", color= T)
144
147. 5 10 15 20 25
020406080100
speed
dist
> abline(lm(dist~speed, cars), col=“red)
148
148. 5 10 15 20 25
020406080100
speed
dist
> lines(lowess(cars), col=“blue”)
149
150. 多變量 – 關連性分析
> library(PerformanceAnalytics)
> chart.Correlation(iris[-5], bg=iris$Species, pch=21)
151
151. 多變量 – 關連性分析 (cont.)
> library(corrplot)
> corrplot(cor(mtcars), method="circle")
152
153. Let’s do it
▪ 實際利用 R 的基礎繪圖 API 進行單變數與
雙變數的視覺化
▪ 請同學們完成
▪ RVisualization-01-One-Variable-Visualization
▪ RVisualization-02-Two-Variables-Visualization
154
165. R 預設的讀取資料技術
▪ 套件中的資料
▪ 預設的資料集,如 iris
▪ 載入套件帶來的資料集 如 library(Lahman)
▪ CSV (Comma Separated Values)
▪ 以逗號區隔的結構化資料 (structured data)
▪ 每一列都有同樣多的資料欄
▪ read.csv
166
166. CSV 的眉眉角角
Year,Make,Model,
1997,Ford,E350
2000,Mercury,Cougar
"1997","Ford","E350“,
1997,Ford,E350,"super, luxurious truck"
1997,Ford,E350,"super, ""luxurious"" truck"
1997,Ford,E350,4.9
1997;Ford;E350;4,9
167
167. 字符編碼
▪ 人類習慣的是 10 進位 (Decimal)
▪ 0, 1, 2, 3, …, 10, …, 15, 16, …, 175
▪ 電腦用的是 2 進位 (Binary, bit) 每個 0, 1 被稱為 bit (位元)
▪ 0, 1, 10, 11, …, 1010, …, 1111, 10000, …, 10101111
▪ 16 進位 (Hexadecimal, Hex) 4 bit 可以表達一個 Hex
▪ 0, 1, 2, 3, …, A, …, F, 10, …, AF
▪ 1 Byte (位元組) = 8 bit 是電腦計算記憶體的基本單位
▪ 1 Byte 可以表達 0 – 255 的值
▪ 正好可以用兩個 Hex Code 表達 (16 = 24)
▪ 00000001 ==> 0000,0001 ==> 01
▪ 10101111 ==> 1010,1111 ==> AF
168
168. 資料在電腦中是如何被儲存的
▪ 現今 32位元的電腦,以 4 Bytes 當作一個 Word
▪ 因此 整數 0L 在記憶體中看起來是 00 00 00 00
▪ 那 “0” 要怎麼儲存呢?
▪ 還記得 factor 嗎?
▪ 我們說過 factor 其實是一種字串的編碼
▪ 將字串 mapping 成數字
▪ 文字在電腦中也是這樣儲存的
▪ "0"=> 在電腦中以 Hex Code 來看是 30
▪ "A": 41, "B": 42, …, "Z": 5A, …, "a": 97
▪ Enter(r): 0D, 換行(n): 0A ASCII 編碼
169
169. 中文編碼
▪ BIG5
▪ "中" : A4 A4
▪ "文" : A4 E5
▪ UTF-8
▪ "中" : E4 B8 AD
▪ "文" : E6 96 87
▪ 以 UTF-8 編碼寫成的 「中文」二字,在電腦看來是
▪ E4 B8 AD E6 96 87
▪ 若是以 BIG5 編碼讀入,會變成 「銝剜 」
▪ 讀取中文檔案時,必須先確定編碼,否則無法正確讀取
170
170. 處理編碼問題
▪ iconv()
▪ R 環境中轉換字元的函式
▪ 請以 ?iconv 閱讀其說明文件
▪ encoding, fileEncoding
▪ R 環境中用來讀取資料的函式常見的參數,用來設
定來源資料的編碼型態
▪ Sys.getlocale(), Sys.setlocale(locale = “cht”)
▪ R 環境用來設定語境的環境變數,可以減少部分編
碼帶來的困擾
171
171. Let’s do it
▪ 實際利用 R 讀取中文編碼的檔案
▪ 請同學們完成 RBasic-07-Loading-Data
172
174. 何謂非結構化資料?
▪ 非結構化資料範例
▪ 64.242.88.10 - - [07/Mar/2004:16:05:49 -0800] "GET
/twiki/bin/edit/Main/Double_bounce_sender?topicparent
=Main.ConfigurationVariables HTTP/1.1" 401 12846
▪ 64.242.88.10 - - [07/Mar/2004:16:06:51 -0800] "GET
/twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=
1.2 HTTP/1.1" 200 4523
175
175. 什麼是 Parsing
▪ 告訴電腦分拆非結構化資料的規則
▪ Domain Knowledge,例如 ip位址:
168.95.192.1
▪ 字元在字串中的位置,如 121E25N
▪ 分隔符號,如逗號、分號、冒號等
▪ Regular Expression 正規表示式
▪ 身分證字號的正規表示式:
▪ ^[A-Z]{1}[1-2]{1}[0-9]{8}$
176
176. Let’s do it
▪ 實際利用 R 處理非結構化的資料
▪ 請同學們完成 RDataEngineer-01-Parsing
177
181. 利用 dplyr 套件整理結構化資料
▪ 函式以整理資料用的動詞命名,簡化整理
資料的思考邏輯,方便程式撰寫
▪ 命名邏輯與 SQL 類似,習慣 SQL 語法的工
程師可以快速上手
▪ 優化過的效能
▪ 效能遠高於 plyr 套件,直逼 data.table 套
件,但是語法比 data.table 平易近人
182
182. 整理資料的動作
▪ filter(): 取出符合條件的資料列 (過濾條件不符的)
▪ arrange(): 依照需求安排(排序)資料
▪ select(): 揀選需要的欄位
▪ distinct():找出獨一無二的值
▪ mutate(): 結合原有欄位,計算新欄位,例如比例…
▪ group_by: 將資料依類別集合做各別的子 data.frame
▪ summarise(): 將整個 data.frame 以一個值概括
▪ sample_n() & sample_frac(): 依數量或比例取樣
183
183. Let’s do it
▪ 實際利用 dplyr 整理讀入 R 環境中的結構化資料
▪ 請同學們完成 RDataEngineer-05-Data-
Manipulation
184
184. 習題題解1
▪ 請問carrier為AA的飛機,是不是 tailnum
都有AA字眼?
> (filter(flights, carrier == "AA", !grepl("AA",
tailnum)) %>% nrow) == 0
> sum(flights$carrier==“AA” & !grepl(“AA”,
flights$tailnum)) == 0
> any(flights$carrier==“AA” &
+ !grepl(“AA”, flights$tailnum))
> all(flights$carrier==“AA” &
+ grepl(“AA”, flights$tailnum))
185
什麼狀況會有 tainum 不是 AA,
但 carrier 是 AA的飛機呢?
為什麼會這樣?
185. 習題題解1 (cont.)
▪ 有事情想不明白,就向資料問答案
> filter(flights, carrier=="AA", !grepl("AA", tailnum)) %>%
"$"("tailnum")
[1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "“
[23] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "“
[45] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "“
[67] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
> filter(flights, carrier=="AA", !grepl("AA", tailnum)) %>% head()
# A tibble: 6 × 16
year month day dep_time dep_delay arr_time arr_delay carrier tailnum
flight origin dest air_time distance hour minute <int> <int> <int>
<int> <dbl> <int> <dbl> <chr> <chr> <int> <chr> <chr> <dbl> <dbl>
<dbl> <dbl>
1 2013 1 2 NA NA NA NA AA 133 JFK LAX NA 2475 NA NA
2 2013 11 24 NA NA NA NA AA 1185 LGA DFW NA 1389 NA NA
3 2013 11 24 NA NA NA NA AA 1691 EWR DFW NA 1372 NA NA
4 2013 11 25 NA NA NA NA AA 1103 LGA DFW NA 1389 NA NA
5 2013 11 25 NA NA NA NA AA 1107 LGA DFW NA 1389 NA NA
6 2013 11 25 NA NA NA NA AA 1381 EWR DFW NA 1372 NA NA
186
186. 習題題解2 - 程式碼壓縮與可讀性
> x1 <- filter(flights, ...)
> x2 <- select(x1, ...)
> x3 <- summarise(x2, ...)
> x3 <- summarise(select(filter(flights, ...) , ...) , ...)
> x3 <-
+ filter(flights, ...) %>%
+ select(...) %>%
+ summarise(...)
Nested Function Call
Pipeline Operation
187
204. Let’s do it
▪ 實際利用 dplyr 整理來自多個資料源的資料
▪ 請同學們完成 RDataEngineer-06-Join
205
205. 習題題解
▪ 房貸餘額與 GDP ,在 aggregate 的過程上,
有什麼不同?
▪ 習題的題目說,以每年一月的資料作為每
年房貸餘額的值,為什麼?這樣做有道理
嘛?
▪ Keep asking questions!
206
207. XML (eXtensible Markup
Language)
▪ 自定義的資料格式
▪ 讓電腦能理解資料意義的資料格式
▪ 標籤、屬性、內容
▪ 用於電腦間的資料交換
<?xml version="1.0"?>
<訊息 類型="小紙條">
<收件人>大元</收件人>
<發件人>小張</發件人>
<主題>問候</主題>
<具體內容>早啊,飯吃了沒? </具體內容>
</訊息> 208
209. XPath (XML Path Language)
<A>
<B>
</C>
</B>
</A>
/A/B/C
<A>
<B>
</C>
</B>
</A>
//B
210
210. JSON (Java Script Object
Notation)
{
"firstName": "John",
"lastName": "Smith",
"sex": "male",
"age": 25
}
211
213. 藉由 DB Connection 操作外部資料
庫
▪ > library(RSQLite)
▪ Loading required package: DBI
▪ Loading required package: methods
▪ > methods("dbConnect")
▪ [1] dbConnect,SQLiteConnection-method
dbConnect,SQLiteDriver-method
▪ see '?methods' for accessing help and source code
214
214. Transaction
▪ ACID
▪ Atomicity: 原子性
▪ Consistency: 一致性
▪ Isolation: 獨立性
▪ Durability: 持久性
▪ 範例:
▪ 提款 => 用戶拿到錢、銀行記錄扣款
▪ 存檔 => 檔案所有部分都正確存入
▪ 多人協作 => 保證變更的順序
215
215. Let’s do it
▪ 實際利用 R 來讀取來自不同型態資料源的
資料
▪ 請同學於課後完成
▪ RDataEngineer-02-XML
▪ RDataEngineer-03-JSON
▪ RDataEngineer-04-Database
216
217. R 的繪圖方法
▪ 內建的基本繪圖 API
▪ 用於繪製各式統計圖形
▪ 以直角座標系為基礎,進行幾何圖形的繪製
▪ ggplot2
▪ Hadley Wickham 所開發,以圖層與
Functional Language 概念為基礎的繪圖 API
218
222. ggplot2 – 類別單變數
> data(diamonds, package = "ggplot2")
> ggplot(diamonds, aes(x=color)) +
+ geom_bar() 223
224. ggplot2 類別 vs. 類別
http://stackoverflow.com/questions/19233365/how-to-create-a-marimekko-
mosaic-plot-inggplot2
225
225. ggplot2 類別 vs. 連續
> ggplot(iris, aes(x=Species, y=Sepal.Width)) +
+ geom_boxplot()
226
226. ggplot2 連續 vs. 連續
> ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length, color=Species)) +
+ geom_point()
227
227. Let’s do it
▪ 實際利用 ggplot2 進行單變數與雙變數的視
覺化
▪ 請同學們完成 RVisualization-03-ggplot2
228
230. Web-based 互動式視覺化解決方案
▪ 與 Java Script 整合產生 Web-base 互動式圖
表網頁
▪ http://www.htmlwidgets.org/
▪ http://yihui.name/recharts/
▪ Shiny
▪ http://shiny.rstudio.com/gallery/
231
231. 來自開放社群的圖資整合套件
▪ 地圖圖資 Rtwmap
▪ https://github.com/wush978/Rtwmap
▪ 社群網路圖資 networkD3
▪ https://cran.r-
project.org/web/packages/networkD3/
▪ 更多新型態的視覺化工具,也不斷開發中
232
232. 地圖圖資
> library(Rtwmap)
> data(county1984)
> random.color <- as.factor(sample(1:3, length(county1984), T))
> color <- rainbow(3)
> county1984$random.color <- random.color
> spplot(county1984, "random.color", col.regions= color, main = "Taiwan Random Color")
233
235. Let’s do it
▪ 實際利用 R 語言繪製互動式視覺化圖形以
及結合地圖資料的資料視覺化
▪ 請各位同學完成 RVisualization-04-
Javascript-And-Maps
236
237. 謝 謝 各 位
許懷中 Hwai-Jung Hsu
hjhsu@mail.fcu.edu.tw
https://tw.linkedin.com/in/hjhsu
Q & A
238