給軟體工程師的不廢話 r 語言精要班

237
在開始之前 (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

Post on 21-Apr-2017

11.868 views

Category:

Data & Analytics


6 download

TRANSCRIPT

Page 1: 給軟體工程師的不廢話 R 語言精要班

在開始之前

(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

Page 2: 給軟體工程師的不廢話 R 語言精要班

R 語言精要

逢甲資工 許懷中

給軟體工程師的

*The material is powered by Wush Wu (吳齊軒) 2

Page 3: 給軟體工程師的不廢話 R 語言精要班

雲端計算、軟體工程

陳昇瑋研究員

多媒體網路與系統實驗室 資料洞察實驗室

陳昇瑋理事長

逢甲大學資訊工程學系系助理教授 逢甲大學大數據中心副主任 逢甲大學資訊系資料工程與應用實驗室 台灣資料科學學會創始會員

3

Page 4: 給軟體工程師的不廢話 R 語言精要班

我是一個

資料科學家

在人生轉角處遇到了教父

4

Page 5: 給軟體工程師的不廢話 R 語言精要班

我的資料科學相關經驗

企業、法人與政府 資料科學人才培訓

線上遊戲玩家 黏著度分析

K-15 學生 快速程度評量

虛寶銷售 預測與成因分析

中華職棒票房 預測與成因分析

5

Page 6: 給軟體工程師的不廢話 R 語言精要班

R 語言簡介

給軟體工程師的 R 語言精要

6

Page 7: 給軟體工程師的不廢話 R 語言精要班

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

7

Page 8: 給軟體工程師的不廢話 R 語言精要班

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=449 8

Page 9: 給軟體工程師的不廢話 R 語言精要班

R 與 Python (cont.)

取自 DSP 謝宗震博士部落格 http://readata.org/r-vs-python/ 9

Page 10: 給軟體工程師的不廢話 R 語言精要班

為什麼學 R ?

精簡、完整、套件多

10

Page 11: 給軟體工程師的不廢話 R 語言精要班

精簡的 R

▪ 一行指令產生數據、並且觀察其分佈 > plot(density(rnorm(100)))

11

Page 12: 給軟體工程師的不廢話 R 語言精要班

精簡的 R (cont.) > plot(density(iris$Petal.Length))

12

Page 13: 給軟體工程師的不廢話 R 語言精要班

精簡的 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

Page 14: 給軟體工程師的不廢話 R 語言精要班

精簡的 R (cont.)

▪ 三行程式碼進行線性回歸 > sample <- read.csv(“sampleData.csv") > model <- lm(value~., data=sample) > summary(model)

14

Page 15: 給軟體工程師的不廢話 R 語言精要班

範例 – A/B Testing (常見於電子商務)

▪ 假如電子商務網站設計了兩種推薦方法

▪ 現在想要比較兩種方法的成果

▪ 方法 A: 在 10000 次點擊中,有 10 個購買

▪ 方法 B: 在 5000 次點擊中,有 3 個購買

▪ 如何知道這兩種方法的轉換率 (購買/點擊) 是否明顯不同?

15

Page 16: 給軟體工程師的不廢話 R 語言精要班

範例 - 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

Page 17: 給軟體工程師的不廢話 R 語言精要班

範例 – 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

Page 18: 給軟體工程師的不廢話 R 語言精要班

涵蓋資料科學所有面向 R 是資料科學的完整解決方案

18

Page 19: 給軟體工程師的不廢話 R 語言精要班

資料蒐集 - R Crawler

▪ httr, html2, rvest, etc.

▪ 參考 Chih-Cheng Liang 在 2015 台灣資料科學愛好者年會上的 Talk

▪ http://chihchengliang.github.io/DSC2015_Crawler/

19

Page 20: 給軟體工程師的不廢話 R 語言精要班

資料整理

▪ 介接各式資料源與資料格式 ▪ 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

Page 21: 給軟體工程師的不廢話 R 語言精要班

統計建模與機器學習

▪ 內建汎用的統計、建模與檢定工具

▪ mean,median

▪ glm

▪ t.test,shapiro.test,ks.test…

▪ 眾多機器學習的熱門套件

▪ randomForest,e1071,xgboost…

21

Page 22: 給軟體工程師的不廢話 R 語言精要班

與巨量資料平台整合

▪ R 本身並不具有巨量資料處理的能力

▪ 可以透過串流或 API 與既有巨量資料平台整合

▪ SparkR,Rhadoop,Rmpi,pbdMPI,…

22

Page 23: 給軟體工程師的不廢話 R 語言精要班

資料呈現 > install.packages(“PerformanceAnalytics”) > suppressPackageStartupMessages(library(PerformanceAnalytics)) > chart.Correlation(iris[-5], bg=iris$Species, pch=21)

23

Page 24: 給軟體工程師的不廢話 R 語言精要班

資料呈現 (cont.)

24

Page 25: 給軟體工程師的不廢話 R 語言精要班

套件眾多、延伸性強的 R

▪ 截至目前為止,R 共有 10,310 種套件,涵蓋 34 種迥異的應用與研究領域

25

Page 26: 給軟體工程師的不廢話 R 語言精要班

眾多的套件 – 串接線上服務

▪ 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

Page 27: 給軟體工程師的不廢話 R 語言精要班

眾多的套件 - 股票分析

> 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

Page 28: 給軟體工程師的不廢話 R 語言精要班

股票分析 (cont.) > chartSeries(TWII, subset = "last 4 months", TA = c(addVo(), addBBands()))

28

Page 29: 給軟體工程師的不廢話 R 語言精要班

眾多的套件 - 棒球分析

> 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

Page 30: 給軟體工程師的不廢話 R 語言精要班

棒球分析 (cont.)

30

Page 31: 給軟體工程師的不廢話 R 語言精要班

棒球分析

> Pitching[Pitching$playerID=="wangch01", c(1,4,13,6,7,20)] playerID teamID IPouts W L ERA 36850 wangch01 NYA 349 8 5 4.02 37547 wangch01 NYA 654 19 6 3.63 38262 wangch01 NYA 598 19 7 3.70 38978 wangch01 NYA 285 8 2 4.07 39706 wangch01 NYA 126 1 6 9.64 41101 wangch01 WAS 187 4 3 4.04 41824 wangch01 WAS 97 2 3 6.68 42547 wangch01 TOR 81 1 2 7.67

31

Page 32: 給軟體工程師的不廢話 R 語言精要班

眾多的套件 - 文字探勘

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

32

*取自 R 社群 2014 閃電秀 by George Chao

Page 33: 給軟體工程師的不廢話 R 語言精要班

文字探勘 – 斷詞

▪ 陳 瑋 Sheng Wei Chen 年會 總召 中央研究院

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

33

*取自 R 社群 2014 閃電秀 by George Chao

Page 34: 給軟體工程師的不廢話 R 語言精要班

文字探勘 – 文字雲

34

*取自 R 社群 2014 閃電秀 by George Chao

Page 36: 給軟體工程師的不廢話 R 語言精要班

R 語言翻轉教室

給軟體工程師的 R 語言精要

36

Page 37: 給軟體工程師的不廢話 R 語言精要班

用 R 語言翻轉教室學 R

▪ 學什麼?

▪ 基本使用知識

▪ 讀取資料與讀取中文

▪ 從公開資料中萃取資訊

▪ 用 R 整理資訊

▪ 用 R 將整理好的資訊繪製統計圖表與地圖

▪ 怎麼學?

▪ 用 R 學 R

37

Page 38: 給軟體工程師的不廢話 R 語言精要班

38

Page 39: 給軟體工程師的不廢話 R 語言精要班

安裝 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

Page 40: 給軟體工程師的不廢話 R 語言精要班

安裝 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

Page 41: 給軟體工程師的不廢話 R 語言精要班

R Studio 的圖形界面

程式碼編輯區

命令列區

其他資訊區

檔案系統區

41

Page 42: 給軟體工程師的不廢話 R 語言精要班

讓我們從命令列開始

▪ R 是一種 script language,使用者可以藉由命令列執行指令

▪ R 的提示符號 >

> "hello world" [1] "hello world" > 1 [1] 1

> 1+1 [1] 2

> 1+ + 1 [1] 2

提示符號變成 + 表示指令未完成

字串

數字

數字運算

42

Page 43: 給軟體工程師的不廢話 R 語言精要班

更多命令 > 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

Page 44: 給軟體工程師的不廢話 R 語言精要班

更多命令 (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

Page 45: 給軟體工程師的不廢話 R 語言精要班

使用編輯介面

▪ 左上角選單 File -> New File -> R Script

▪ 在編輯區 ▪ 鍵入 1 + 1 按下 Ctrl + Enter,觀察命令列區 ▪ 鍵入 1/2 按下 Enter ▪ 鍵入 2*2 按下 Ctrl + Alt + B,觀察命令列區

▪ Tab 鍵在編輯介面下一樣可用

▪ 養成在編輯介面寫程式的習慣

45

Page 46: 給軟體工程師的不廢話 R 語言精要班

其他介面操作

▪ 觀察其他資訊區 History 分頁底下有什麼?

▪ 觀察檔案資訊區 Files、Packages 分頁底下有什麼?

46

Page 47: 給軟體工程師的不廢話 R 語言精要班

安裝與使用 R 套件

▪ 利用 R Studio 安裝與載入

▪ 檔案系統區 > Packages 分頁

▪ 使用命令列安裝套件 > install.packages("套件名稱", repos = "套件庫網址)

▪ 使用命令列載入套件 > library(套件名稱)

47

Page 48: 給軟體工程師的不廢話 R 語言精要班

安裝用來學習 R 的 R 套件 - swirl

▪ 請在命令列執行下列指令以安裝互動課程所需的套件

▪ 請在命令列執行下列指令以載入並啟動課程

> source("http://wush978.github.io/R/init-swirl.R")

> library(swirl) > swirl()

48

Page 49: 給軟體工程師的不廢話 R 語言精要班

互動式學習環境

49

Page 50: 給軟體工程師的不廢話 R 語言精要班

互動式學習環境 (cont.)

請以 Google 或 Facebook 帳號登入

50

Page 51: 給軟體工程師的不廢話 R 語言精要班

互動式學習環境 (cont.)

51

Page 52: 給軟體工程師的不廢話 R 語言精要班

互動式學習環境 (cont.)

▪ RBasic: 講解 R 的基礎知識與語法

▪ RDataEngineer: 講解載入資料至 R 環境,以及清理、整理資料的作法

▪ RVisualization: 講解利用 R 視覺化資料的知識

▪ RProgramming: 介紹 R 的程式功能

52

Page 53: 給軟體工程師的不廢話 R 語言精要班

本次課程的學習路徑

▪ R 語言入門 ▪ RBasic-01~06

▪ R 語言視覺化基礎 ▪ RVisualization-01~02

▪ R 語言資料工程 ▪ Rbasic-07

▪ RDataEngineer-01, 05, 06

▪ R 語言視覺化進階 ▪ RVisualization-03, 04

53

Page 54: 給軟體工程師的不廢話 R 語言精要班

Let’s Do It

▪ 實際操作 swirl 課程,請各位同學進行

▪ Hello-DataScienceAndR

▪ RBasic-01-Introduction

▪ 如有任何問題,如亂碼、不知該如何進行,請舉手向助教或講師洽詢

54

Page 55: 給軟體工程師的不廢話 R 語言精要班

R 語言的資料型態

給軟體工程師的 R 語言精要

55

Page 56: 給軟體工程師的不廢話 R 語言精要班

資料的種類

▪ 名目資料 (Nomnial)

▪ 順序資料 (Ordinal)

▪ 區間資料 (Interval)

▪ 比值資料 (Ratio)

56

Page 57: 給軟體工程師的不廢話 R 語言精要班

名目資料 (Nominal)

▪ Name

▪ 畢業學校:交大、台大、清大……

▪ 車輛廠牌:Toyota, VW, Benz

▪ 分類

▪ 性別:男、女、其他

▪ 產業:金融、資訊、製造……

▪ 屬性上的有無

▪ 年收入>100萬:是、否

▪ 資料的先後、順序沒有意義 57

Page 58: 給軟體工程師的不廢話 R 語言精要班

名目資料 (cont.)

58

Page 59: 給軟體工程師的不廢話 R 語言精要班

順序資料 (Ordinal)

▪ 先後的意義

▪ 硬度表

(1) 滑石, (2) 石膏, (3) 方解石, (4) 螢石, (5) 磷灰石,

(6) 正長石, (7) 石英, (8) 黃玉, (9) 剛玉, (10) 金剛石

▪ CPBL 戰績排名

(1) Lamigo (2) 中信 (3) 義大 (4) 統一……

▪ 有序的名目資料

▪ 不確定間隔的意義

59

Page 60: 給軟體工程師的不廢話 R 語言精要班

區間資料 (Interval)

▪ 溫度

▪ 攝氏溫標: 0⁰C, 100⁰C

▪ 時間

▪ 秒、分、時、日、年

▪ 各式度量衡

▪ 長度:公尺、公寸、英尺、英吋

▪ 重量:公斤、磅

▪ 具有固定間隔的順序資料

60

Page 61: 給軟體工程師的不廢話 R 語言精要班

比值資料 (Ratio)

▪ 絕對溫度

▪ 克氏溫標: 0⁰K = -273.15⁰C

▪ 股價

▪ 票面 10 元

▪ 公司營收

▪ 具有自然參考點(零點)的區間資料

61

Page 62: 給軟體工程師的不廢話 R 語言精要班

比值資料 (cont.)

62

Page 63: 給軟體工程師的不廢話 R 語言精要班

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

Page 64: 給軟體工程師的不廢話 R 語言精要班

向量化的資料型態

▪ 在 R 之中所有的資料都是向量

▪ 什麼意思?

64

Page 65: 給軟體工程師的不廢話 R 語言精要班

何為向量?

▪向量是數學、物理學和工程科學等多個自然科學中的基本概念,指一個同時具有大小和方向的幾何對象,因常常以箭頭符號標示以區別於其它量而得名。直觀上,向量通常被標示為一個帶箭頭的線段。線段的長度可以表示向量的大小,而箭頭所指的方向也就是向量的方向。 From Wiki

65

Page 66: 給軟體工程師的不廢話 R 語言精要班

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

Page 67: 給軟體工程師的不廢話 R 語言精要班

R 的基本資料型態

▪ 邏輯向量 (logical)

▪ 整數向量 (integer)

▪ 數值向量 (numeric):

▪ 字串向量 (character):

68

Page 68: 給軟體工程師的不廢話 R 語言精要班

邏輯向量 (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

Page 69: 給軟體工程師的不廢話 R 語言精要班

整數向量

▪ 每個整數佔4 Bytes – 長整數

> c(1L, 2L, 3L, 4L, 0xaL) [1] 1 2 3 4 10

70

Page 70: 給軟體工程師的不廢話 R 語言精要班

數值向量

▪ 每個數值大小 8 bytes (雙精確浮點數)

> c(1.0, .1, 1e-2, 1e2, 1.2e2) [1] 1.00 0.10 0.01 100.00 120.00

71

Page 71: 給軟體工程師的不廢話 R 語言精要班

字串向量

▪ NULL 結尾的字串向量

> c("1","a","中文") [1] "1" "a" "中文" > c("a\0b") Error: nul character not allowed (line 1)

72

Page 72: 給軟體工程師的不廢話 R 語言精要班

R 物件

▪ 上述基本資料型態都可以視為是「R物件」

▪ 事實上 R 裡面的所有東西都是一種 R 物件

▪ 資料、函數、環境、外部指標

73

Page 73: 給軟體工程師的不廢話 R 語言精要班

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

Page 74: 給軟體工程師的不廢話 R 語言精要班

Let’s do it!

▪ 實際操作 R 的基礎資料型態

▪ RBasic-02-Data-Structure-Vectors

▪ RBasic-03-Data-Structure-Object

75

Page 75: 給軟體工程師的不廢話 R 語言精要班

習題題解

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

Page 76: 給軟體工程師的不廢話 R 語言精要班

習題題解 (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

Page 77: 給軟體工程師的不廢話 R 語言精要班

習題題解 (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

Page 78: 給軟體工程師的不廢話 R 語言精要班

習題題解 (cont.)

> power1 > 7e9 [1] FALSE FALSE FALSE TRUE TRUE > year1 [1] 87 88 89 90 91

> year1[power1 > 7e9] [1] 90 91

79

Page 79: 給軟體工程師的不廢話 R 語言精要班

習題題解 (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

Page 80: 給軟體工程師的不廢話 R 語言精要班

FACTOR R 語言的資料結構

81

Page 81: 給軟體工程師的不廢話 R 語言精要班

factor?

▪ 內建的 factor 範例

> head(CO2$Type) [1] Quebec Quebec Quebec Quebec Quebec Quebec Levels: Quebec Mississippi

82

Page 82: 給軟體工程師的不廢話 R 語言精要班

看似字串,其實不然

> 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

Page 83: 給軟體工程師的不廢話 R 語言精要班

factor -名目資料的編碼

> attributes(CO2$Type) $levels [1] "Quebec" "Mississippi" $class [1] "factor"

84

Page 84: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際操作 R 的 Factor

▪ 請同學們完成 RBasic-04-Factors

85

Page 85: 給軟體工程師的不廢話 R 語言精要班

MATRIX & ARRAY 給軟體工程師的 R 語言精要

86

Page 86: 給軟體工程師的不廢話 R 語言精要班

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

Page 87: 給軟體工程師的不廢話 R 語言精要班

藉由 Attributes 操弄 Matrix

> attributes(x) <- NULL > x [1] 1 2 3 4

88

Page 88: 給軟體工程師的不廢話 R 語言精要班

Matrix 的物件結構

X 1:4

dim(X) C(2L, 2L)

4 2

3 1

89

Page 89: 給軟體工程師的不廢話 R 語言精要班

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

Page 90: 給軟體工程師的不廢話 R 語言精要班

優化過的 Matrix

▪ 方便操作的 API

▪ 優化過的運算效能 (BLAS)

91

Page 91: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際操作 R 的 Matrix 以及 Array

▪ 請同學們完成 RBasic-05-Arrays-Matrices

92

Page 92: 給軟體工程師的不廢話 R 語言精要班

習題題解

▪ 𝑦 = 𝑋 ∙ 𝛽 為什麼不直接 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

Page 93: 給軟體工程師的不廢話 R 語言精要班

LIST – R 物件的向量

給軟體工程師的 R 語言精要

94

Page 94: 給軟體工程師的不廢話 R 語言精要班

基本資料型態的向量必須是同質的

> 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

Page 95: 給軟體工程師的不廢話 R 語言精要班

如何應對實務上不同型態的資料?

▪ R 物件可以視為是任何型態的向量

▪ R 物件的向量,就可以儲存不同型態的資料

96

Page 96: 給軟體工程師的不廢話 R 語言精要班

整數向量

> 1:5 [1] 1 2 3 4 5

97

Page 97: 給軟體工程師的不廢話 R 語言精要班

> x <- list(1:5, c("a","b")) > x [[1]] [1] 1 2 3 4 5 [[2]] [1] "a" "b"

list

98

Page 98: 給軟體工程師的不廢話 R 語言精要班

[

> x[1] [[1]] [1] 1 2 3 4 5 > class(x[1]) [1] "list"

99

Page 99: 給軟體工程師的不廢話 R 語言精要班

[[

> x[[1]] [1] 1 2 3 4 5 > class(x[[1]]) [1] “integer"

100

Page 100: 給軟體工程師的不廢話 R 語言精要班

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

Page 101: 給軟體工程師的不廢話 R 語言精要班

> 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.)

Page 102: 給軟體工程師的不廢話 R 語言精要班

$

> x <- list(a = 1:5, b = c("a", "b")) > x$a [1] 1 2 3 4 5 > x$b [1] "a" "b"

103

Page 103: 給軟體工程師的不廢話 R 語言精要班

從 list 到 data.frame

▪ list 提供了處理異質資料的工具

▪ R 的物件導向系統就是以 list 為基礎

▪ 將 list 用於結構化資料仍然不甚直覺 ▪ 不像矩陣提供許多方便的 API

▪ 所以我們有了 data.frame ▪ 用於結構化資料的 R 物件 ▪ 兼具 list 與 matrix 的特性

104

Page 104: 給軟體工程師的不廢話 R 語言精要班

DATA FRAME 給軟體工程師的 R 語言精要

105

Page 105: 給軟體工程師的不廢話 R 語言精要班

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

Page 106: 給軟體工程師的不廢話 R 語言精要班

看看 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

Page 107: 給軟體工程師的不廢話 R 語言精要班

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

Page 108: 給軟體工程師的不廢話 R 語言精要班

但又可以當作 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

Page 109: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際操作 R 的 List 以及 Data Frame

▪ 請同學們完成 RBasic-06-List-DataFrame

110

Page 110: 給軟體工程師的不廢話 R 語言精要班

習題題解

這個 𝑦 = 𝑋 ∙ 𝛽 到底是在搞什麼?

matrix 與 data.frame 兩章的習題,讓同學體驗了現今資料科學最常用的一種技法 –

統計建模

111

Page 111: 給軟體工程師的不廢話 R 語言精要班

習題題解 (cont.)

y: 想要預測的事物 - 反應變數 X: 可以觀測到的眾多變因 - 自變數

ß: 找尋 X, y 之間的關係

以利用 X 預測 y – 模型

112

Page 112: 給軟體工程師的不廢話 R 語言精要班

習題題解 (cont.)

▪ 真實的 y 其實不可知,因為測量總是有誤差,

▪ 測量值與真實值之間的差距叫 error

▪ 模型的預測值與測量值之間的差距叫 residual (殘差)

113

Page 113: 給軟體工程師的不廢話 R 語言精要班

習題題解 (cont.) > plot(cars) > abline(lm(dist~speed, cars), col=2)

線性迴歸,建立一個殘差最小 的線性模型 (模型是一條直線)

114

Page 114: 給軟體工程師的不廢話 R 語言精要班

R 與數據模型

給軟體工程師的 R 語言精要

115

Page 115: 給軟體工程師的不廢話 R 語言精要班

數據模型的 API 設計模式

▪ 線性代數介面

▪ 方程式 (Formula) 介面

116

Page 116: 給軟體工程師的不廢話 R 語言精要班

線性代數介面

▪ X: 一個代表解釋變數的矩陣

▪ y: 一個代表應變數的向量

▪ …: 代表演算法的參數

> g <- lm(X, y, ...)

117

Page 117: 給軟體工程師的不廢話 R 語言精要班

方程式介面

▪ 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

Page 118: 給軟體工程師的不廢話 R 語言精要班

實務討論

給軟體工程師的 R 語言精要

119

Page 119: 給軟體工程師的不廢話 R 語言精要班

R 需要將所有資料放入記憶體

▪ 記憶體的大小直接影響可處理資料的 scale

120

Page 120: 給軟體工程師的不廢話 R 語言精要班

估計記憶體使用量

▪ 向量的大小

▪ 基本資料型態的大小乘上向量長度

▪ 加上 metadata (class, attributes, etc.)

121

Page 121: 給軟體工程師的不廢話 R 語言精要班

object.size

> object.size(logical(0)) 40 bytes > object.size(rep(TRUE, 1000)) 4040 bytes > object.size(rep(TRUE, 1e6)) 4000040 bytes

122

Page 122: 給軟體工程師的不廢話 R 語言精要班

object.size (cont.)

> object.size(logical(0)) 40 bytes > object.size(seq(1L, by = 1L, length = 1e3)) 4040 bytes > object.size(seq(1L, by = 1L, length = 1e6)) 4000040 bytes

123

Page 123: 給軟體工程師的不廢話 R 語言精要班

object.size

> object.size(numeric(0)) 40 bytes > object.size(seq(0, by = 1L, length = 1e3)) 8040 bytes > object.size(seq(0, by = 1L, length = 1e6)) 8000040 bytes

124

Page 124: 給軟體工程師的不廢話 R 語言精要班

字串向量的記憶體用量較難估計

> speaker <- readLines("speaker.txt") > speaker[2] [1] "年會總召, 中央研究院資訊科學研究所/ 研究員" > length(speaker) [1] 216 > file.size("speaker.txt") [1] 18464 > object.size(speaker) 24664 bytes

125

Page 125: 給軟體工程師的不廢話 R 語言精要班

實務經驗

▪ 在真的把資料搞進 R 裡面之前

▪ 先估計記憶體用量

▪ 抓會有幾個 “0”

126

Page 126: 給軟體工程師的不廢話 R 語言精要班

R 的記憶體處理機制

▪ Garbage Collection => gc()

▪ Pass by Value

▪ Copy on Write

127

Page 127: 給軟體工程師的不廢話 R 語言精要班

Garbage Collection

▪ 釋放不使用的記憶體

▪ 關閉不使用的檔案連線

128

Page 128: 給軟體工程師的不廢話 R 語言精要班

Pass by Value

▪ 傳入函式中的參數

▪ 會 copy 一份副本在函式中使用

▪ 在函式中的修改,不會影響到原本傳入參數在外部的值

129

Page 129: 給軟體工程師的不廢話 R 語言精要班

Copy on Write

▪ 只有物件被修改的時候,才會進行複製

130

Page 130: 給軟體工程師的不廢話 R 語言精要班

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

Page 131: 給軟體工程師的不廢話 R 語言精要班

利用 R 語言內建視覺化函式庫 觀察資料

給軟體工程師的 R 語言精要

132

Page 132: 給軟體工程師的不廢話 R 語言精要班

R 的繪圖引擎 X11

Unix 作業系統的 X-Window GUI

Windows 用於 Windows 作業系統

Quartz MAC OS X 系統

Postscript 用於印表機或是建立 PS 文件

pdf, png, jpeg 用於建立特定格式的檔案

html 與 javascript 用於建立網頁上的互動式圖表

133

Page 133: 給軟體工程師的不廢話 R 語言精要班

R的基本繪圖 API ▪ 高階繪圖指令

▪ 依據輸入的資料產生完整的圖形 ▪ plot, pie, hist, boxplot, barplot, … ▪ 清空先前繪圖結果

▪ 低階繪圖指令

▪ 修飾、裝飾當前的圖形

▪ lines, points, legend, text, polygon, …

▪ 繪圖引擎參數控制

▪ par

134

Page 134: 給軟體工程師的不廢話 R 語言精要班

基本繪圖 API 的精神

▪ 以直角座標系統繪製各種幾何圖形

▪ 與模型相結合,依據模型的型態繪製結果plot.lm, rpart::plot.rpart

135

Page 135: 給軟體工程師的不廢話 R 語言精要班

以資料為出發點的視覺化類型

單變數 類別型變數

連續型變數

雙變數

類別 vs. 類別

類別 vs. 連續

連續 vs. 連續

多變數

136

Page 136: 給軟體工程師的不廢話 R 語言精要班

類別型變數

> pie(table(iris$Species))

137

Page 137: 給軟體工程師的不廢話 R 語言精要班

連續型變數

> par(mfrow = c(1,2)) > plot(density(iris$Sepal.Length)) > hist(iris$Sepal.Length)

138

Page 138: 給軟體工程師的不廢話 R 語言精要班

> d1 <- sample(1:6, 100, replace=TRUE) > hist(d1)

139

Page 139: 給軟體工程師的不廢話 R 語言精要班

> d1 <- sample(1:6, 100, replace=TRUE) > d1 <- sample(1:6, 100, replace=TRUE) > hist(d1+d2)

140

Page 140: 給軟體工程師的不廢話 R 語言精要班

> hist(d1+d2, prob=TRUE) > plot(density(d1+d2, bw=“SJ”), col=“red”)

141

Page 141: 給軟體工程師的不廢話 R 語言精要班

> d1 <- sample(1:6, 10000, replace=TRUE) > hist(d1)

142

Page 142: 給軟體工程師的不廢話 R 語言精要班

> hist(d1+d2, prob=TRUE) > plot(density(d1+d2, bw=1), col=“red”)

143

Page 143: 給軟體工程師的不廢話 R 語言精要班

類別 vs. 類別

> data(Titanic) > mosaicplot(~Sex + Survived, data = Titanic, + main = "Survival on The Titanic", color= T)

144

Page 144: 給軟體工程師的不廢話 R 語言精要班

> plot(Sepal.Length~Species, iris)

類別 vs. 連續

145

Page 145: 給軟體工程師的不廢話 R 語言精要班

146

Page 146: 給軟體工程師的不廢話 R 語言精要班

> plot(dist~speed, cars)

連續 vs. 連續

147

Page 147: 給軟體工程師的不廢話 R 語言精要班

5 10 15 20 25

02

04

06

08

01

00

speed

dis

t

> abline(lm(dist~speed, cars), col=“red)

148

Page 148: 給軟體工程師的不廢話 R 語言精要班

5 10 15 20 25

02

04

06

08

01

00

speed

dis

t

> lines(lowess(cars), col=“blue”)

149

Page 149: 給軟體工程師的不廢話 R 語言精要班

多變量

> plot(iris)

150

Page 150: 給軟體工程師的不廢話 R 語言精要班

多變量 – 關連性分析

> library(PerformanceAnalytics) > chart.Correlation(iris[-5], bg=iris$Species, pch=21)

151

Page 151: 給軟體工程師的不廢話 R 語言精要班

多變量 – 關連性分析 (cont.)

> library(corrplot) > corrplot(cor(mtcars), method="circle")

152

Page 152: 給軟體工程師的不廢話 R 語言精要班

> plot(~read+math, data=hsb, + col=col.sex, pch=pch.schtyp, + cex=cex.science)

153

Page 153: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 R 的基礎繪圖 API 進行單變數與雙變數的視覺化

▪ 請同學們完成

▪ RVisualization-01-One-Variable-Visualization

▪ RVisualization-02-Two-Variables-Visualization

154

Page 154: 給軟體工程師的不廢話 R 語言精要班

數據模型與視覺化

給軟體工程師的 R 語言精要

155

Page 155: 給軟體工程師的不廢話 R 語言精要班

Linear Regression

> plot(cars) > abline(lm(dist~speed, cars), col=2)

156

Page 156: 給軟體工程師的不廢話 R 語言精要班

Linear Regression (cont.)

> g <- lm(dist ~ speed, cars) > par(mfrow = c(2,2)) > plot(g) 157

Page 157: 給軟體工程師的不廢話 R 語言精要班

Lowess Regression 的視覺化

> plot(cars, main = "lowess(cars)") > lines(lowess(cars), col = 2)

158

Page 158: 給軟體工程師的不廢話 R 語言精要班

Smoothing Method Regression

> library(sm) > with(cars, sm.regression(dist, speed, method="aicc", + col = "red", model="linear")

159

Page 159: 給軟體工程師的不廢話 R 語言精要班

Decision Tree

> library(rpart) > library(rpart.plot) > rpart.plot(rpart(Species ~., iris))

160

Page 160: 給軟體工程師的不廢話 R 語言精要班

多變量 PCA

> library(ade4) > g <- dudi.pca(iris[,-5], scan = F) > scatter(g)

161

Page 161: 給軟體工程師的不廢話 R 語言精要班

R 的資料處理技術

給軟體工程師的 R 語言精要

162

Page 162: 給軟體工程師的不廢話 R 語言精要班

關於讀取資料的互動式課程

▪ 讀取儲存於磁碟的資料 ▪ RBasic-07-Loading-Data

▪ 讀取來自不同資料源與格式的資料 ▪ RDataEngineer-02-XML ▪ RDataEngineer-03-JSON ▪ RDataEngineer-04-Database ▪ Optional 課程,進度超前的同學可以自行練習

163

Page 163: 給軟體工程師的不廢話 R 語言精要班

關於處理資料的互動式課程

▪ 利用領域知識處理非結構化資料 ▪ RDataEngineer-01-Parsing

▪ 處理與進一步整理結構化資料的技術 ▪ RDataEngineer-05-Data-Manipulation

▪ 將不同的表格資料融合運用 ▪ RDataEngineer-06-Join

164

Page 164: 給軟體工程師的不廢話 R 語言精要班

將磁碟中的資料讀進 R 環境

給軟體工程師的 R 語言精要

165

Page 165: 給軟體工程師的不廢話 R 語言精要班

R 預設的讀取資料技術

▪ 套件中的資料

▪ 預設的資料集,如 iris

▪ 載入套件帶來的資料集 如 library(Lahman)

▪ CSV (Comma Separated Values)

▪ 以逗號區隔的結構化資料 (structured data)

▪ 每一列都有同樣多的資料欄

▪ read.csv

166

Page 166: 給軟體工程師的不廢話 R 語言精要班

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

Page 167: 給軟體工程師的不廢話 R 語言精要班

字符編碼 ▪ 人類習慣的是 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

Page 168: 給軟體工程師的不廢話 R 語言精要班

資料在電腦中是如何被儲存的

▪ 現今 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

Page 169: 給軟體工程師的不廢話 R 語言精要班

中文編碼

▪ BIG5 ▪ "中" : A4 A4 ▪ "文" : A4 E5

▪ UTF-8 ▪ "中" : E4 B8 AD ▪ "文" : E6 96 87

▪ 以 UTF-8 編碼寫成的 「中文」二字,在電腦看來是

▪ E4 B8 AD E6 96 87

▪ 若是以 BIG5 編碼讀入,會變成 「銝剜 」

▪ 讀取中文檔案時,必須先確定編碼,否則無法正確讀取

170

Page 170: 給軟體工程師的不廢話 R 語言精要班

處理編碼問題

▪ iconv() ▪ R 環境中轉換字元的函式

▪ 請以 ?iconv 閱讀其說明文件

▪ encoding, fileEncoding ▪ R 環境中用來讀取資料的函式常見的參數,用來設定來源資料的編碼型態

▪ Sys.getlocale(), Sys.setlocale(locale = “cht”) ▪ R 環境用來設定語境的環境變數,可以減少部分編碼帶來的困擾

171

Page 171: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 R 讀取中文編碼的檔案

▪ 請同學們完成 RBasic-07-Loading-Data

172

Page 172: 給軟體工程師的不廢話 R 語言精要班

實務觀點

read.csv(…, fileEncoding= "utf8")

read.csv(…, fileEncoding= “big5")

遇到大檔

library(data.table)

data.table::fread

173

Page 173: 給軟體工程師的不廢話 R 語言精要班

處理非結構化資料

R 語言與資料處理

174

Page 174: 給軟體工程師的不廢話 R 語言精要班

何謂非結構化資料?

▪ 非結構化資料範例 ▪ 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

Page 175: 給軟體工程師的不廢話 R 語言精要班

什麼是 Parsing

▪ 告訴電腦分拆非結構化資料的規則

▪ Domain Knowledge,例如 ip位址: 168.95.192.1

▪ 字元在字串中的位置,如 121E25N

▪ 分隔符號,如逗號、分號、冒號等

▪ Regular Expression 正規表示式

▪ 身分證字號的正規表示式:

▪ ^[A-Z]{1}[1-2]{1}[0-9]{8}$

176

Page 176: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 R 處理非結構化的資料

▪ 請同學們完成 RDataEngineer-01-Parsing

177

Page 177: 給軟體工程師的不廢話 R 語言精要班

習題題解

▪ 強大的 strsplit,向量化計算的威力

▪ 全形、半形符號混雜怎麼切?

178

Page 178: 給軟體工程師的不廢話 R 語言精要班

處理以及操作結構化資料

給軟體工程師的 R 語言精要

179

Page 179: 給軟體工程師的不廢話 R 語言精要班

R 的結構化資料來源

▪ 內部: data.frame、data.table

▪ 外部: 關聯式資料庫、格式健全良好的 CSV 檔案

180

Page 180: 給軟體工程師的不廢話 R 語言精要班

整理結構化資料

▪ 分類報表

▪ 男性、女性、重度消費者、輕度消費者

▪ 分時報表

▪ 月報、季報、年報

▪ 從 raw data 中計算指標

▪ 安打/打數 = 打擊率、總得分/場次 = 平均得分

181

Page 181: 給軟體工程師的不廢話 R 語言精要班

利用 dplyr 套件整理結構化資料

▪ 函式以整理資料用的動詞命名,簡化整理資料的思考邏輯,方便程式撰寫

▪ 命名邏輯與 SQL 類似,習慣 SQL 語法的工程師可以快速上手

▪ 優化過的效能

▪ 效能遠高於 plyr 套件,直逼 data.table 套件,但是語法比 data.table 平易近人

182

Page 182: 給軟體工程師的不廢話 R 語言精要班

整理資料的動作

▪ filter(): 取出符合條件的資料列 (過濾條件不符的)

▪ arrange(): 依照需求安排(排序)資料

▪ select(): 揀選需要的欄位

▪ distinct(): 找出獨一無二的值

▪ mutate(): 結合原有欄位,計算新欄位,例如比例…

▪ group_by: 將資料依類別集合做各別的子 data.frame

▪ summarise(): 將整個 data.frame 以一個值概括

▪ sample_n() & sample_frac(): 依數量或比例取樣

183

Page 183: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 dplyr 整理讀入 R 環境中的結構化資料

▪ 請同學們完成 RDataEngineer-05-Data-Manipulation

184

Page 184: 給軟體工程師的不廢話 R 語言精要班

習題題解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的飛機呢?

為什麼會這樣?

Page 185: 給軟體工程師的不廢話 R 語言精要班

習題題解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

Page 186: 給軟體工程師的不廢話 R 語言精要班

習題題解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

Page 187: 給軟體工程師的不廢話 R 語言精要班

結合不同的資料源

R 語言與資料處理

188

Page 188: 給軟體工程師的不廢話 R 語言精要班

多資料源的價值

▪ flights

▪ flights + weather

▪ flights + weather + airports

189

Page 189: 給軟體工程師的不廢話 R 語言精要班

inner_join

All columns from both X and Y Duplicate if multiple matching

190

Page 190: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

191

Page 191: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

192

Page 192: 給軟體工程師的不廢話 R 語言精要班

semi_join

Only columns from X No duplication

193

Page 193: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

194

Page 194: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

195

Page 195: 給軟體工程師的不廢話 R 語言精要班

left_join

All columns from both X and Y NA’s for missing values

196

Page 196: 給軟體工程師的不廢話 R 語言精要班

right_join

All columns from both X and Y NA’s for missing values

197

Page 197: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

198

Page 198: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

199

Page 199: 給軟體工程師的不廢話 R 語言精要班

anti_join

Only columns from X

200

Page 200: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

201

Page 201: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

202

Page 202: 給軟體工程師的不廢話 R 語言精要班

full_join

All columns from both X and Y NA’s for missing values

203

Page 203: 給軟體工程師的不廢話 R 語言精要班

*from https://stat545-ubc.github.io/bit001_dplyr-cheatsheet.html

204

Page 204: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 dplyr 整理來自多個資料源的資料

▪ 請同學們完成 RDataEngineer-06-Join

205

Page 205: 給軟體工程師的不廢話 R 語言精要班

習題題解

▪ 房貸餘額與 GDP ,在 aggregate 的過程上,有什麼不同?

▪ 習題的題目說,以每年一月的資料作為每年房貸餘額的值,為什麼?這樣做有道理嘛?

▪ Keep asking questions!

206

Page 206: 給軟體工程師的不廢話 R 語言精要班

讀取格式迥異的資料

R 語言與資料處理

207

Page 207: 給軟體工程師的不廢話 R 語言精要班

XML (eXtensible Markup Language)

▪ 自定義的資料格式

▪ 讓電腦能理解資料意義的資料格式

▪ 標籤、屬性、內容

▪ 用於電腦間的資料交換 <?xml version="1.0"?> <訊息 類型="小紙條"> <收件人>大元</收件人> <發件人>小張</發件人> <主題>問候</主題> <具體內容>早啊,飯吃了沒? </具體內容> </訊息>

208

Page 208: 給軟體工程師的不廢話 R 語言精要班

HTML (HyperText Markup Language)

▪ 用於網頁的 Markup Language

▪ 具有固定規範

▪ 形式上不如 XML 自由,然而文法上較不嚴謹

209

Page 209: 給軟體工程師的不廢話 R 語言精要班

XPath (XML Path Language)

<A> <B> </C> </B> </A>

/A/B/C

<A> <B> </C> </B> </A>

//B

210

Page 210: 給軟體工程師的不廢話 R 語言精要班

JSON (Java Script Object Notation)

{ "firstName": "John", "lastName": "Smith", "sex": "male", "age": 25 }

211

Page 211: 給軟體工程師的不廢話 R 語言精要班

JSON (cont.)

▪ 字串:"firstName", "John"

▪ 數字: 25

▪ 陣列: [1, 2, "3"]

▪ 物件: {

▪ "a" : 1,

▪ "b" : "string",

▪ "c" : { "c1" : 1 }

▪ }

212

Page 212: 給軟體工程師的不廢話 R 語言精要班

Database

▪ 非結構化資料: 純文字

▪ 半結構化資料: CSV, XML, JSON

▪ 結構化資料: 關聯式資料庫 (data.frame)

213

Page 213: 給軟體工程師的不廢話 R 語言精要班

藉由 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

Page 214: 給軟體工程師的不廢話 R 語言精要班

Transaction

▪ ACID ▪ Atomicity: 原子性

▪ Consistency: 一致性

▪ Isolation: 獨立性

▪ Durability: 持久性

▪ 範例: ▪ 提款 => 用戶拿到錢、銀行記錄扣款

▪ 存檔 => 檔案所有部分都正確存入

▪ 多人協作 => 保證變更的順序

215

Page 215: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 R 來讀取來自不同型態資料源的資料

▪ 請同學於課後完成

▪ RDataEngineer-02-XML

▪ RDataEngineer-03-JSON

▪ RDataEngineer-04-Database

216

Page 216: 給軟體工程師的不廢話 R 語言精要班

R 語言視覺化進階

給軟體工程師的 R 語言精要

217

Page 217: 給軟體工程師的不廢話 R 語言精要班

R 的繪圖方法

▪ 內建的基本繪圖 API

▪ 用於繪製各式統計圖形

▪ 以直角座標系為基礎,進行幾何圖形的繪製

▪ ggplot2

▪ Hadley Wickham 所開發,以圖層與 Functional Language 概念為基礎的繪圖 API

218

Page 218: 給軟體工程師的不廢話 R 語言精要班

GGPLOT2 給軟體工程師的 R 語言精要

219

Page 219: 給軟體工程師的不廢話 R 語言精要班

Reference

Leland Wilkinson, “The Grammar of Graphics,” Springer, ISBN 978-0-387-98774-3, 2015

220

Page 220: 給軟體工程師的不廢話 R 語言精要班

ggplot2 的基礎精神

▪ R 語言內建的基礎繪圖 API 是一種以紙筆來繪圖的設計思想

▪ ggplot2 是一種以繪圖物件為主的設計思想

221

Page 221: 給軟體工程師的不廢話 R 語言精要班

ggplot2 對 R 的影響

▪ 大量以 ggplot2 為骨幹的套件

222

Page 222: 給軟體工程師的不廢話 R 語言精要班

ggplot2 – 類別單變數

> data(diamonds, package = "ggplot2") > ggplot(diamonds, aes(x=color)) + + geom_bar() 223

Page 223: 給軟體工程師的不廢話 R 語言精要班

ggplot2 – 連續單變數

> ggplot(diamonds, aes(x=price)) + + geom_density()

224

Page 224: 給軟體工程師的不廢話 R 語言精要班

ggplot2 類別 vs. 類別

http://stackoverflow.com/questions/19233365/how-to-create-a-marimekko-mosaic-plot-inggplot2 225

Page 225: 給軟體工程師的不廢話 R 語言精要班

ggplot2 類別 vs. 連續

> ggplot(iris, aes(x=Species, y=Sepal.Width)) + + geom_boxplot()

226

Page 226: 給軟體工程師的不廢話 R 語言精要班

ggplot2 連續 vs. 連續

> ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length, color=Species)) + + geom_point()

227

Page 227: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 ggplot2 進行單變數與雙變數的視覺化

▪ 請同學們完成 RVisualization-03-ggplot2

228

Page 228: 給軟體工程師的不廢話 R 語言精要班

R 語言與互動式網頁以及地圖資料視覺化

給軟體工程師的 R 語言精要

229

Page 229: 給軟體工程師的不廢話 R 語言精要班

新世代對於視覺化的需求

▪ 面對高維度資料,使用者需要直接對圖進行操作,以降低思考的複雜度

▪ 資料的種類更廣泛,除了離散、數值型資料以外,還包含「圖資」等傳統統計圖形不曾處理的資料

230

Page 230: 給軟體工程師的不廢話 R 語言精要班

Web-based 互動式視覺化解決方案

▪ 與 Java Script 整合產生 Web-base 互動式圖表網頁

▪ http://www.htmlwidgets.org/

▪ http://yihui.name/recharts/

▪ Shiny

▪ http://shiny.rstudio.com/gallery/

231

Page 231: 給軟體工程師的不廢話 R 語言精要班

來自開放社群的圖資整合套件

▪ 地圖圖資 Rtwmap

▪ https://github.com/wush978/Rtwmap

▪ 社群網路圖資 networkD3

▪ https://cran.r-project.org/web/packages/networkD3/

▪ 更多新型態的視覺化工具,也不斷開發中

232

Page 232: 給軟體工程師的不廢話 R 語言精要班

地圖圖資 > 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

Page 233: 給軟體工程師的不廢話 R 語言精要班

社群網路視覺化

> library(networkD3) > data(MisLinks);data(MisNodes) > forceNetwork(Links = MisLinks, Nodes= MisNodes, Source = "source", Target = "target", + Value = "value", NodeID = "name", Group = "group", opacity = 0.4, zoom = T)

234

Page 235: 給軟體工程師的不廢話 R 語言精要班

Let’s do it

▪ 實際利用 R 語言繪製互動式視覺化圖形以及結合地圖資料的資料視覺化

▪ 請各位同學完成 RVisualization-04-Javascript-And-Maps

236

Page 236: 給軟體工程師的不廢話 R 語言精要班

237

Page 237: 給軟體工程師的不廢話 R 語言精要班

謝 謝 各 位

許懷中 Hwai-Jung Hsu [email protected]

https://tw.linkedin.com/in/hjhsu

Q & A

238