SlideShare a Scribd company logo
1 of 50
Download to read offline
Rによるデータ処理入門
Hiroki
今日のテーマ
○ データを加工する
× 統計解析を行う
今日のテーマ
1. データを読み込む
2. データを加工する
3. データを可視化する
今日のテーマ
• 極力、既存サンプルデータを使う
• 極力、パッケージに頼る
• 関連する項目も説明する ☕ ☕ ☕
1.データを読み込む
• テキストファイル: data <- read.table(ファイル名)
• CSVファイル: data <- read.csv(ファイル名)
• 固定長ファイル data <- read.fwf(ファイル名)
• バイナリ(.RData), .Rファイル: source(ファイル名)
• データベース(ODBC利用): conn <- RODBC::odbcConnect(dsn, …)
data <- RODBC:: sqlQuery(conn, クエリ)
• XML data <- xmlToDataFrame(ファイル名)
• shapeファイル(.shp) data <- maptools::readShapePoly(ファイル名)
• iniファイル data <- raster::readIniFile
1.データを読み込む
☕ ☕ ☕ データフレーム
• 最もよく使われるデータ構造、スプレッドシートのようなもの
• 行列形式で「列:変数」毎の操作が可能
dim(data) 3, 3
data[1, 2] ABC
data$商品番号 101, 102, 103
行番号 商品番号 商品名 売り上げ
1 101 ABC 12345
2 102 DEF 678
3 103 GHI 910
data <- data.frame(商品番号=c(101, 102, 103),商品名=c(“ABC”,“DEF”,“GHI”),売り上げ=c(12345,678,910))
1.データを読み込む
☕ ☕ ☕ データの型とファクタ(factor)
• データの型を確認する
class(data) data.frame
str(data) 商品番号: int
商品名: Factor
売り上げ: int
• Factorとして読み込ませない
read.csv(…, stringsAsFactors=FALSE)
行番号 商品番号 商品名 売り上げ
1 101 ABC 12345
2 102 DEF 678
3 103 GHI 910
デフォルトではファクタ型で
読み込まれる
1.データを読み込む
☕ ☕ ☕ データの型とファクタ(factor)
• データの型を変更する
as(data, 変更後の型)
as.変更後の型(data)
(例) as.character(data$商品名)
as.matrix(data)
行番号 商品番号 商品名 売り上げ
1 101 ABC 12345
2 102 DEF 678
3 103 GHI 910
1.データを読み込む
☕ ☕ ☕ データの中身を確認する
• 型を確認する: str(data)
• 上から n 行を確認する: head(data, n)
• 下から n 行を確認する: tail(data, n)
• ヘッダーを確認する: names(data)
• 各列(変数)の統計量: summary(data)
⇒ data を iris、 n を 3 として実行
商品番号 商品名 売り上げ
Min.
1st Qu.
Median
Mean
3rd Qu.
Max.
summary(data)
1.データを読み込む
☕ ☕ ☕ RDataファイル
• バイナリ形式のファイル
• 容量を劇的に削減できる
• 複数のオブジェクトを保存できる
save(df1, df2, …, file=ファイル名)
*csvの場合 write.csv(df1, ファイル名)
0
5
10
15
20
25
30
35
CSV RData
MB
1.データを読み込む
data <- read.csv(“ファイル名.csv”, stringsAsFactor=FALSE)
str(data)
next <- function(data$商品名, …)
write.csv(ans, “ans.csv”)
行番号 商品番号 商品名 売り上げ
1 101 ABC 12345
2 102 DEF 678
3 103 GHI 910
*Rにおいて .(ドット)は単なる文字の一つ(正規表現は除く)
2.データを加工する
• 簡単な操作
抽出: data[1:2, ] 1, 2行目
subset(data, 商品名==“ABC”) 商品名=ABCの行
data[data$商品名 ==“ABC”, ] 商品名=ABCの行
data[, 3] 3列目(売り上げ)
data$売り上げ 3列目(売り上げ)
四則演算: data[, 1] + 1 1列目全要素に+1
data[, 1] + data[, 3] 1列目+3列目
2.データを加工する
• 簡単な操作・続
文字列: grep(data$商品名, “ABC”) 商品名=ABCの行番号
grepl(data$商品名, “ABC”) 各行で商品名=ABCか
gsub(“A”, “X”, data$商品名) 置換 A→X
paste(data$売り上げ, “円”) 文字列の結合
並べ替え: sort(data$売り上げ) 売り上げ順にソート
order(data$売り上げ) 各行の売り上げ順位
data[order(data$売り上げ), ] 売り上げ順にソート
2.データを加工する
• 簡単な操作・続続
FORループ: for (i in 1:n){…}
(例) 各列の和を計算する
ans <- c(0, 0, 0)
for (i in 1:nrow(data)){
ans[i, ] <- sum(data[1,], na.rm=TRUE)
}
行番号 X … Y
1 101 12345
2 102 678
3 103 910
配列はc(…)
欠損値NAは無視する。
これが無いと、NAが混在していた場合、
結果もNAとなってしまう。
2.データを加工する
行番号 X … Y
1 101 12345
2 102 678
3 103 910
☕ ☕ ☕ apply系の関数
FORは遅い
• FORの代わりにapplyを使う
apply(data, 1, sum, na.rm=T)
1: 行方向
2: 列方向
関数
類似関数
sapply, vapply, lapply, mapply
{xts} rollapply, …
2.データを加工する
行番号 X … Y
1 101 12345
2 102 678
3 103 910
☕ ☕ ☕ SQLに慣れている場合
• {sqldf}パッケージでSQL文をそのまま使う
library(sqldf)
sqldf(“select * from data”)
*SQLiteを使用
注意!
• .(ドット)が入らないようにする
• 時間データを処理できない
(文字列か整数に直す等の処理)
2.データを加工する {dplyr} +α
たぶん一番便利なパッケージ
2.データを加工する {dplyr} +α
☕ ☕ ☕ パッケージ
• インストール:install.packages(パッケージ名)
install_github(パッケージ名)
• 呼び出し: library(パッケージ名)
require(パッケージ名)
requireはTRUE(インストールされている)、FALSEを返す。
(例) if(!require(“dplyr”)){
install.packages(“dplyr”)
require(dplyr)
}
RstudioのGUIを利用する
インストールする
呼び出す
2.データを加工する {dplyr} +α
☕ ☕ ☕ Rの記法
• 標準: ans <- func1(data, …)
ans <- func2(func1(data))
ans <- func3(func2(fanc1(data)))
• チェーン記法: ans <- data %>% func1()
ans <- data %>% func1() %>% func2()
ans <- data %>% func1() %>% func2() %>% func3()
処理の順に書き下すことができる
2.データを加工する {dplyr} +α
データを…
• グループ毎に計算
• 整形
• 追加、抽出、ソート
• 結合
Fruits <- Fruits[,-7]
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
2.データを加工する {dplyr} +α
• グループ毎に計算する
Fruits %>%
group_by(Fruit) %>%
summarise(avg_sales=mean(Sales, na.rm=T),
sum_sales=sum(Sales, na.rm=T))
• group_by: グループ化する項目
• summarise: グループ毎に計算
Fruit avg_sales sum_sales
Apples 99.33333 298
Bananas 86.66667 260
Oranges 95.66667 287
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
2.データを加工する {dplyr} +α
• グループ毎に計算する
Fruits %>%
group_by(Fruit) %>%
do(avg_sales=mean(.$Sales, na.rm=T),
corr=lm(.$Sales~.$Profit)$coefficients[2]) %>%
as.data.frame()
• group_by: グループ化する項目
• do: グループ毎に計算
• .(ドット) Fruits
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
lm: 線形回帰
lm(y~x, data)
coefficients[2]: 傾き
Fruit avg_sales sum_sales
Apples 99.333333 1.1498195
Bananas 86.666667 1.5930233
Oranges 95.666667 -0.384615
2.データを加工する {dplyr} +α
• 整形する: 縦方向
{tidyr} を利用
tidyr::gather
FruitsEdited <- Fruits %>%
gather(var, val, -Fruit, -Year, -Location)
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location var val
Apples 2008 West Sales 98
Apples 2009 West Sales 111
Apples 2010 West Sales 89
Oranges 2008 East Sales 96
Bananas 2008 East Sales 85
Oranges 2009 East Sales 93
Bananas 2009 East Sales 94
Oranges 2010 East Sales 98
Bananas 2010 East Sales 81
Apples 2008 West Expenses 78
Apples 2009 West Expenses 79
Apples 2010 West Expenses 76
Oranges 2008 East Expenses 81
Bananas 2008 East Expenses 76
Oranges 2009 East Expenses 80
Bananas 2009 East Expenses 78
Oranges 2010 East Expenses 91
Bananas 2010 East Expenses 71
Apples 2008 West Profit 20
Apples 2009 West Profit 32
Apples 2010 West Profit 13
Oranges 2008 East Profit 15
Bananas 2008 East Profit 9
Oranges 2009 East Profit 13
Bananas 2009 East Profit 16
Oranges 2010 East Profit 7
Bananas 2010 East Profit 10FruitsEdited
Fruits
2.データを加工する {dplyr} +α
• 整形する: 横方向
{tidyr} を利用
tidyr::spread
Fruits <- FruitsEdited %>%
spread(var, val)
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location var val
Apples 2008 West Sales 98
Apples 2009 West Sales 111
Apples 2010 West Sales 89
Oranges 2008 East Sales 96
Bananas 2008 East Sales 85
Oranges 2009 East Sales 93
Bananas 2009 East Sales 94
Oranges 2010 East Sales 98
Bananas 2010 East Sales 81
Apples 2008 West Expenses 78
Apples 2009 West Expenses 79
Apples 2010 West Expenses 76
Oranges 2008 East Expenses 81
Bananas 2008 East Expenses 76
Oranges 2009 East Expenses 80
Bananas 2009 East Expenses 78
Oranges 2010 East Expenses 91
Bananas 2010 East Expenses 71
Apples 2008 West Profit 20
Apples 2009 West Profit 32
Apples 2010 West Profit 13
Oranges 2008 East Profit 15
Bananas 2008 East Profit 9
Oranges 2009 East Profit 13
Bananas 2009 East Profit 16
Oranges 2010 East Profit 7
Bananas 2010 East Profit 10FruitsEdited
Fruits
2.データを加工する {dplyr} +α
• 整形する: 列の結合
{tidyr} を利用
tidyr::unite
FruitsUnited <- Fruits %>%
unite(ID, Fruit, Year, sep=":")
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
ID Location Sales Expenses Profit
Apples:2008 West 98 78 20
Apples:2009 West 111 79 32
Apples:2010 West 89 76 13
Oranges:2008 East 96 81 15
Bananas:2008 East 85 76 9
Oranges:2009 East 93 80 13
Bananas:2009 East 94 78 16
Oranges:2010 East 98 91 7
Bananas:2010 East 81 71 10
Fruits
FruitsUnitedまとめる項目(元)まとめる項目(まとめ先)
2.データを加工する {dplyr} +α
• 整形する: 列の分解
{tidyr} を利用
tidyr::unite
Fruits <- FruitsUnited %>%
separate(ID, c(“Fruit”, “Year”), sep=":")
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
ID Location Sales Expenses Profit
Apples:2008 West 98 78 20
Apples:2009 West 111 79 32
Apples:2010 West 89 76 13
Oranges:2008 East 96 81 15
Bananas:2008 East 85 76 9
Oranges:2009 East 93 80 13
Bananas:2009 East 94 78 16
Oranges:2010 East 98 91 7
Bananas:2010 East 81 71 10
Fruits
FruitsUnited分解先分解元
2.データを加工する {dplyr} +α
• 追加、抽出、ソート
列の追加や変更 dplyr::mutate
Fruits %>%
mutate(over100 = (Sales>100))
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
over100
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
2.データを加工する {dplyr} +α
• 追加、抽出、ソート
列の抽出 dplyr::select
Fruits %>%
mutate(over100 = (Sales>100)) %>%
dplyr::select(-over100)
• dplyr:: とするのは、MASS::selectと区別するため
• dplyr::select(Fruit:Proft)も同じ結果
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
over100
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
2.データを加工する {dplyr} +α
• 追加、抽出、ソート
行の抽出 dplyr::filter
Fruits %>%
dplyr::filter(Fruit==“Apples”)
• dplyr:: とするのは、stats::filterと区別するため
• Fruits %>% subset(Fruit==“Apples”) や
Fruits[Fruits$Fruit==“Apples”,] も同じ結果
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
2.データを加工する {dplyr} +α
• 追加、抽出、ソート
ソート dplyr::arrange
Fruits %>%
arrange(Fruit, Sales)
• arrange(優先順位1, 優先順位2, …)
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location Sales Expenses Profit
Apples 2010 West 89 76 13
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Bananas 2010 East 81 71 10
Bananas 2008 East 85 76 9
Bananas 2009 East 94 78 16
Oranges 2009 East 93 80 13
Oranges 2008 East 96 81 15
Oranges 2010 East 98 91 7
2.データを加工する {dplyr} +α
• データを結合する
dplyr::left_join
C <- data.frame(Fruit=c(“Apples”, “Bananas”, “Hatena”),
Color=c(“green”, “yellow”, “blue”))
Fruits %>%
left_join(data.frame(C, by=“Fruit”)
right_joinはCにFruitsを結合させる
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Color
Apples green
Bananas yellow
Hatena blue
Fruit Year Location Sales Expenses Profit Color
Apples 2008 West 98 78 20 green
Apples 2009 West 111 79 32 green
Apples 2010 West 89 76 13 green
Oranges 2008 East 96 81 15 NA
Bananas 2008 East 85 76 9 yellow
Oranges 2009 East 93 80 13 NA
Bananas 2009 East 94 78 16 yellow
Oranges 2010 East 98 91 7 NA
Bananas 2010 East 81 71 10 yellow
C
Fruits
2.データを加工する {dplyr} +α
• データを結合する
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Bananas 2009 East 94 78 16
Oranges 2010 East 98 91 7
Bananas 2010 East 81 71 10
Fruit Year Location Sales Expenses Profit Color
Apples 2008 West 98 78 20 green
Apples 2009 West 111 79 32 green
Apples 2010 West 89 76 13 green
Oranges 2008 East 96 81 15 NA
Bananas 2008 East 85 76 9 yellow
Oranges 2009 East 93 80 13 NA
Bananas 2009 East 94 78 16 yellow
Oranges 2010 East 98 91 7 NA
Bananas 2010 East 81 71 10 yellow
Hatena NA NA NA A NA blue
Fruit Color
Apples green
Bananas yellow
Hatena blue
C
Fruit Year Location Sales Expenses Profit Color
Apples 2008 West 98 78 20 green
Apples 2009 West 111 79 32 green
Apples 2010 West 89 76 13 green
Bananas 2008 East 85 76 9 yellow
Bananas 2009 East 94 78 16 yellow
Bananas 2010 East 81 71 10 yellow
Fruit
2.データを加工する {dplyr} +α
• データを結合する
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
cbind(Fruits1, Fruits2)
Fruit Year Location Sales Expenses Profit
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
Fruits1 <- Fruits[1:3,]
Fruits2 <- Fruits[c(4:6),]
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Fruit Year Location Sales Expenses Profit
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
rbind(Fruits1, Fruits2)
Fruit Year Location Sales Expenses Profit
Apples 2008 West 98 78 20
Apples 2009 West 111 79 32
Apples 2010 West 89 76 13
Fruit Year Location Sales Expenses Profit
Oranges 2008 East 96 81 15
Bananas 2008 East 85 76 9
Oranges 2009 East 93 80 13
3.データを可視化する
データの可視化…
• すべての基本: plot
• 少し凝ったグラフ: ggplot
• インタラクティブなグラフ: googleVis等
• その他(地図、3D…)
3.データを可視化する
• plot関数
plot(x, y, …)
plot(cars,
main = "練習",
xlab = "スピード",
ylab = "距離",
col = "blue")
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
10 18
10 26
10 34
11 17
11 28
12 14
12 20
… …
cars
3.データを可視化する
• plot関数
plot(x, y, …)
plot(cars,
main = "練習",
xlab = "スピード",
ylab = "距離",
col = "blue")
lines(cars, col=“red”) #折れ線の追加
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
10 18
10 26
10 34
11 17
11 28
12 14
12 20
… …
cars
3.データを可視化する
• plot関数
plot(x, y, …)
plot(cars,
main = "練習",
xlab = "スピード",
ylab = "距離",
col = "blue“,
type = “b”)
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
10 18
10 26
10 34
11 17
11 28
12 14
12 20
… …
cars
3.データを可視化する
• plot関数
plot(x, y, …)
plot(cars,
main = "練習",
xlab = "スピード",
ylab = "距離",
col = "blue“,
type = “l”)
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
10 18
10 26
10 34
11 17
11 28
12 14
12 20
… …
cars
3.データを可視化する
• plot関数
plot(x, y, …)
plot(cars,
main = "練習",
xlab = "スピード",
ylab = "距離",
col = "blue“,
pch = 19)
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
10 18
10 26
10 34
11 17
11 28
12 14
12 20
… …
cars
3.データを可視化する
☕ ☕ ☕ plotの形状(pch)
• pch: 数値の場合1~25、文字列の場合任意
par(mfrow=c(2, 1))
plot(1:26, pch=1:26)
plot(1:26, pch=LETTERS)
LETTERS = c(“A”, “B”, … “Z”)
Yの値、Xのデフォルト値は
1:length(Y)
画面の分割:
mfrow(m,n) … m×nに分割
余白が足りない ⇒ 余白の調整はpar(mar())
3.データを可視化する
☕ ☕ ☕ plot画面(graphics device)を閉じる
• dev.off() 現在のデバイスを閉じる
• graphics.off() 全てのデバイスを閉じる
• Rstudio上でも可能
全てのデバイスを閉じる
3.データを可視化する
• その他
hist()とboxplot()
boxplot(cars)
par(mfrow=c(2,1))
hist(cars$speed)
hist(cars$dist)
3.データを可視化する
☕ ☕ ☕ プロットが重なる場合
(例) N(0, 10)に従う乱数を1000個作りプロットする
set.seed(1)
test <- rnorm(1000, 0, 10)
plot(test, pch=19)
• {scales} alphaを使い半透明にする
library(scales)
plot(test, pch=19, alpha(“black”, 0.2))
α値の指定
個数 μ σ
乱数を固定
3.データを可視化する
• 少し凝ったグラフ {ggplot2}
ggplot(data, aes(x, y)) + geom_...
• aes aesthentics(審美属性)。x, y, 色,サイズ
• geom_ プロットの形式
geom_line, geom_points, geom_histogram等
• + ggplotでは+で重ね描きする
(例) irisデータで密度推定
ggplot (iris, aes (x = Sepal.Length, y = Sepal.Width, colour = Species)) + stat_density2d ()
3.データを可視化する
• 少し凝ったグラフ {ggplot2}
その他の例
ggplot(iris, aes(x=Sepal.Length, fill=Species)) +
geom_density(position='identity', alpha=.3)
ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point(aes(color = Species), size = 2.5)
3.データを可視化する
☕ ☕ ☕ ggplotの便利さ
データ加工と可視化を同時に行う
ggplot(FruitsEdited, aes(Year, val)) +
geom_line() +
facet_grid(Fruit~var)
facet_grid(y~x)により
デバイス(画面)を分割し
(x, y)に該当するグラフを描画する。
このときx軸、y軸は自動で統一される。
Fruit Year Location var val
Apples 2008 West Sales 98
Apples 2009 West Sales 111
Apples 2010 West Sales 89
Oranges 2008 East Sales 96
Bananas 2008 East Sales 85
Oranges 2009 East Sales 93
Bananas 2009 East Sales 94
Oranges 2010 East Sales 98
Bananas 2010 East Sales 81
Apples 2008 West Expenses 78
Apples 2009 West Expenses 79
Apples 2010 West Expenses 76
Oranges 2008 East Expenses 81
Bananas 2008 East Expenses 76
Oranges 2009 East Expenses 80
Bananas 2009 East Expenses 78
Oranges 2010 East Expenses 91
Bananas 2010 East Expenses 71
Apples 2008 West Profit 20
Apples 2009 West Profit 32
Apples 2010 West Profit 13
Oranges 2008 East Profit 15
Bananas 2008 East Profit 9
Oranges 2009 East Profit 13
Bananas 2009 East Profit 16
Oranges 2010 East Profit 7
Bananas 2010 East Profit 10
FruitsEdited
自動で振り分けてくれる
軸も統一されている
3.データを可視化する
• インタラクティブなグラフ {googleVis}
M <- gvisMotionChart(Fruits, "Fruit", "Year",
options=list(state='{"showTrails":false};'))
plot(M)
3.データを可視化する
• インタラクティブなグラフ {googleVis}
M <- gvisMotionChart(Fruits, “Fruit”, “Year”, options=list(state='{"showTrails":false};'))
plot(M)
3.データを可視化する
• その他
ありがとうございました
?function_name

More Related Content

Recently uploaded

Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Danieldanielhu54
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものですiPride Co., Ltd.
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNetToru Tamaki
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A surveyToru Tamaki
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムsugiuralab
 
TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdftaisei2219
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略Ryo Sasaki
 
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...Toru Tamaki
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Yuma Ohgami
 

Recently uploaded (9)

Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Daniel
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものです
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システム
 
TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdf
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
 
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
 

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Featured (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

Rデータ処理入門

  • 5. 1.データを読み込む • テキストファイル: data <- read.table(ファイル名) • CSVファイル: data <- read.csv(ファイル名) • 固定長ファイル data <- read.fwf(ファイル名) • バイナリ(.RData), .Rファイル: source(ファイル名) • データベース(ODBC利用): conn <- RODBC::odbcConnect(dsn, …) data <- RODBC:: sqlQuery(conn, クエリ) • XML data <- xmlToDataFrame(ファイル名) • shapeファイル(.shp) data <- maptools::readShapePoly(ファイル名) • iniファイル data <- raster::readIniFile
  • 6. 1.データを読み込む ☕ ☕ ☕ データフレーム • 最もよく使われるデータ構造、スプレッドシートのようなもの • 行列形式で「列:変数」毎の操作が可能 dim(data) 3, 3 data[1, 2] ABC data$商品番号 101, 102, 103 行番号 商品番号 商品名 売り上げ 1 101 ABC 12345 2 102 DEF 678 3 103 GHI 910 data <- data.frame(商品番号=c(101, 102, 103),商品名=c(“ABC”,“DEF”,“GHI”),売り上げ=c(12345,678,910))
  • 7. 1.データを読み込む ☕ ☕ ☕ データの型とファクタ(factor) • データの型を確認する class(data) data.frame str(data) 商品番号: int 商品名: Factor 売り上げ: int • Factorとして読み込ませない read.csv(…, stringsAsFactors=FALSE) 行番号 商品番号 商品名 売り上げ 1 101 ABC 12345 2 102 DEF 678 3 103 GHI 910 デフォルトではファクタ型で 読み込まれる
  • 8. 1.データを読み込む ☕ ☕ ☕ データの型とファクタ(factor) • データの型を変更する as(data, 変更後の型) as.変更後の型(data) (例) as.character(data$商品名) as.matrix(data) 行番号 商品番号 商品名 売り上げ 1 101 ABC 12345 2 102 DEF 678 3 103 GHI 910
  • 9. 1.データを読み込む ☕ ☕ ☕ データの中身を確認する • 型を確認する: str(data) • 上から n 行を確認する: head(data, n) • 下から n 行を確認する: tail(data, n) • ヘッダーを確認する: names(data) • 各列(変数)の統計量: summary(data) ⇒ data を iris、 n を 3 として実行 商品番号 商品名 売り上げ Min. 1st Qu. Median Mean 3rd Qu. Max. summary(data)
  • 10. 1.データを読み込む ☕ ☕ ☕ RDataファイル • バイナリ形式のファイル • 容量を劇的に削減できる • 複数のオブジェクトを保存できる save(df1, df2, …, file=ファイル名) *csvの場合 write.csv(df1, ファイル名) 0 5 10 15 20 25 30 35 CSV RData MB
  • 11. 1.データを読み込む data <- read.csv(“ファイル名.csv”, stringsAsFactor=FALSE) str(data) next <- function(data$商品名, …) write.csv(ans, “ans.csv”) 行番号 商品番号 商品名 売り上げ 1 101 ABC 12345 2 102 DEF 678 3 103 GHI 910 *Rにおいて .(ドット)は単なる文字の一つ(正規表現は除く)
  • 12. 2.データを加工する • 簡単な操作 抽出: data[1:2, ] 1, 2行目 subset(data, 商品名==“ABC”) 商品名=ABCの行 data[data$商品名 ==“ABC”, ] 商品名=ABCの行 data[, 3] 3列目(売り上げ) data$売り上げ 3列目(売り上げ) 四則演算: data[, 1] + 1 1列目全要素に+1 data[, 1] + data[, 3] 1列目+3列目
  • 13. 2.データを加工する • 簡単な操作・続 文字列: grep(data$商品名, “ABC”) 商品名=ABCの行番号 grepl(data$商品名, “ABC”) 各行で商品名=ABCか gsub(“A”, “X”, data$商品名) 置換 A→X paste(data$売り上げ, “円”) 文字列の結合 並べ替え: sort(data$売り上げ) 売り上げ順にソート order(data$売り上げ) 各行の売り上げ順位 data[order(data$売り上げ), ] 売り上げ順にソート
  • 14. 2.データを加工する • 簡単な操作・続続 FORループ: for (i in 1:n){…} (例) 各列の和を計算する ans <- c(0, 0, 0) for (i in 1:nrow(data)){ ans[i, ] <- sum(data[1,], na.rm=TRUE) } 行番号 X … Y 1 101 12345 2 102 678 3 103 910 配列はc(…) 欠損値NAは無視する。 これが無いと、NAが混在していた場合、 結果もNAとなってしまう。
  • 15. 2.データを加工する 行番号 X … Y 1 101 12345 2 102 678 3 103 910 ☕ ☕ ☕ apply系の関数 FORは遅い • FORの代わりにapplyを使う apply(data, 1, sum, na.rm=T) 1: 行方向 2: 列方向 関数 類似関数 sapply, vapply, lapply, mapply {xts} rollapply, …
  • 16. 2.データを加工する 行番号 X … Y 1 101 12345 2 102 678 3 103 910 ☕ ☕ ☕ SQLに慣れている場合 • {sqldf}パッケージでSQL文をそのまま使う library(sqldf) sqldf(“select * from data”) *SQLiteを使用 注意! • .(ドット)が入らないようにする • 時間データを処理できない (文字列か整数に直す等の処理)
  • 18. 2.データを加工する {dplyr} +α ☕ ☕ ☕ パッケージ • インストール:install.packages(パッケージ名) install_github(パッケージ名) • 呼び出し: library(パッケージ名) require(パッケージ名) requireはTRUE(インストールされている)、FALSEを返す。 (例) if(!require(“dplyr”)){ install.packages(“dplyr”) require(dplyr) } RstudioのGUIを利用する インストールする 呼び出す
  • 19. 2.データを加工する {dplyr} +α ☕ ☕ ☕ Rの記法 • 標準: ans <- func1(data, …) ans <- func2(func1(data)) ans <- func3(func2(fanc1(data))) • チェーン記法: ans <- data %>% func1() ans <- data %>% func1() %>% func2() ans <- data %>% func1() %>% func2() %>% func3() 処理の順に書き下すことができる
  • 20. 2.データを加工する {dplyr} +α データを… • グループ毎に計算 • 整形 • 追加、抽出、ソート • 結合 Fruits <- Fruits[,-7] Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10
  • 21. 2.データを加工する {dplyr} +α • グループ毎に計算する Fruits %>% group_by(Fruit) %>% summarise(avg_sales=mean(Sales, na.rm=T), sum_sales=sum(Sales, na.rm=T)) • group_by: グループ化する項目 • summarise: グループ毎に計算 Fruit avg_sales sum_sales Apples 99.33333 298 Bananas 86.66667 260 Oranges 95.66667 287 Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10
  • 22. 2.データを加工する {dplyr} +α • グループ毎に計算する Fruits %>% group_by(Fruit) %>% do(avg_sales=mean(.$Sales, na.rm=T), corr=lm(.$Sales~.$Profit)$coefficients[2]) %>% as.data.frame() • group_by: グループ化する項目 • do: グループ毎に計算 • .(ドット) Fruits Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 lm: 線形回帰 lm(y~x, data) coefficients[2]: 傾き Fruit avg_sales sum_sales Apples 99.333333 1.1498195 Bananas 86.666667 1.5930233 Oranges 95.666667 -0.384615
  • 23. 2.データを加工する {dplyr} +α • 整形する: 縦方向 {tidyr} を利用 tidyr::gather FruitsEdited <- Fruits %>% gather(var, val, -Fruit, -Year, -Location) Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location var val Apples 2008 West Sales 98 Apples 2009 West Sales 111 Apples 2010 West Sales 89 Oranges 2008 East Sales 96 Bananas 2008 East Sales 85 Oranges 2009 East Sales 93 Bananas 2009 East Sales 94 Oranges 2010 East Sales 98 Bananas 2010 East Sales 81 Apples 2008 West Expenses 78 Apples 2009 West Expenses 79 Apples 2010 West Expenses 76 Oranges 2008 East Expenses 81 Bananas 2008 East Expenses 76 Oranges 2009 East Expenses 80 Bananas 2009 East Expenses 78 Oranges 2010 East Expenses 91 Bananas 2010 East Expenses 71 Apples 2008 West Profit 20 Apples 2009 West Profit 32 Apples 2010 West Profit 13 Oranges 2008 East Profit 15 Bananas 2008 East Profit 9 Oranges 2009 East Profit 13 Bananas 2009 East Profit 16 Oranges 2010 East Profit 7 Bananas 2010 East Profit 10FruitsEdited Fruits
  • 24. 2.データを加工する {dplyr} +α • 整形する: 横方向 {tidyr} を利用 tidyr::spread Fruits <- FruitsEdited %>% spread(var, val) Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location var val Apples 2008 West Sales 98 Apples 2009 West Sales 111 Apples 2010 West Sales 89 Oranges 2008 East Sales 96 Bananas 2008 East Sales 85 Oranges 2009 East Sales 93 Bananas 2009 East Sales 94 Oranges 2010 East Sales 98 Bananas 2010 East Sales 81 Apples 2008 West Expenses 78 Apples 2009 West Expenses 79 Apples 2010 West Expenses 76 Oranges 2008 East Expenses 81 Bananas 2008 East Expenses 76 Oranges 2009 East Expenses 80 Bananas 2009 East Expenses 78 Oranges 2010 East Expenses 91 Bananas 2010 East Expenses 71 Apples 2008 West Profit 20 Apples 2009 West Profit 32 Apples 2010 West Profit 13 Oranges 2008 East Profit 15 Bananas 2008 East Profit 9 Oranges 2009 East Profit 13 Bananas 2009 East Profit 16 Oranges 2010 East Profit 7 Bananas 2010 East Profit 10FruitsEdited Fruits
  • 25. 2.データを加工する {dplyr} +α • 整形する: 列の結合 {tidyr} を利用 tidyr::unite FruitsUnited <- Fruits %>% unite(ID, Fruit, Year, sep=":") Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 ID Location Sales Expenses Profit Apples:2008 West 98 78 20 Apples:2009 West 111 79 32 Apples:2010 West 89 76 13 Oranges:2008 East 96 81 15 Bananas:2008 East 85 76 9 Oranges:2009 East 93 80 13 Bananas:2009 East 94 78 16 Oranges:2010 East 98 91 7 Bananas:2010 East 81 71 10 Fruits FruitsUnitedまとめる項目(元)まとめる項目(まとめ先)
  • 26. 2.データを加工する {dplyr} +α • 整形する: 列の分解 {tidyr} を利用 tidyr::unite Fruits <- FruitsUnited %>% separate(ID, c(“Fruit”, “Year”), sep=":") Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 ID Location Sales Expenses Profit Apples:2008 West 98 78 20 Apples:2009 West 111 79 32 Apples:2010 West 89 76 13 Oranges:2008 East 96 81 15 Bananas:2008 East 85 76 9 Oranges:2009 East 93 80 13 Bananas:2009 East 94 78 16 Oranges:2010 East 98 91 7 Bananas:2010 East 81 71 10 Fruits FruitsUnited分解先分解元
  • 27. 2.データを加工する {dplyr} +α • 追加、抽出、ソート 列の追加や変更 dplyr::mutate Fruits %>% mutate(over100 = (Sales>100)) Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 over100 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
  • 28. 2.データを加工する {dplyr} +α • 追加、抽出、ソート 列の抽出 dplyr::select Fruits %>% mutate(over100 = (Sales>100)) %>% dplyr::select(-over100) • dplyr:: とするのは、MASS::selectと区別するため • dplyr::select(Fruit:Proft)も同じ結果 Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 over100 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
  • 29. 2.データを加工する {dplyr} +α • 追加、抽出、ソート 行の抽出 dplyr::filter Fruits %>% dplyr::filter(Fruit==“Apples”) • dplyr:: とするのは、stats::filterと区別するため • Fruits %>% subset(Fruit==“Apples”) や Fruits[Fruits$Fruit==“Apples”,] も同じ結果 Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13
  • 30. 2.データを加工する {dplyr} +α • 追加、抽出、ソート ソート dplyr::arrange Fruits %>% arrange(Fruit, Sales) • arrange(優先順位1, 優先順位2, …) Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location Sales Expenses Profit Apples 2010 West 89 76 13 Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Bananas 2010 East 81 71 10 Bananas 2008 East 85 76 9 Bananas 2009 East 94 78 16 Oranges 2009 East 93 80 13 Oranges 2008 East 96 81 15 Oranges 2010 East 98 91 7
  • 31. 2.データを加工する {dplyr} +α • データを結合する dplyr::left_join C <- data.frame(Fruit=c(“Apples”, “Bananas”, “Hatena”), Color=c(“green”, “yellow”, “blue”)) Fruits %>% left_join(data.frame(C, by=“Fruit”) right_joinはCにFruitsを結合させる Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Color Apples green Bananas yellow Hatena blue Fruit Year Location Sales Expenses Profit Color Apples 2008 West 98 78 20 green Apples 2009 West 111 79 32 green Apples 2010 West 89 76 13 green Oranges 2008 East 96 81 15 NA Bananas 2008 East 85 76 9 yellow Oranges 2009 East 93 80 13 NA Bananas 2009 East 94 78 16 yellow Oranges 2010 East 98 91 7 NA Bananas 2010 East 81 71 10 yellow C Fruits
  • 32. 2.データを加工する {dplyr} +α • データを結合する Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Bananas 2009 East 94 78 16 Oranges 2010 East 98 91 7 Bananas 2010 East 81 71 10 Fruit Year Location Sales Expenses Profit Color Apples 2008 West 98 78 20 green Apples 2009 West 111 79 32 green Apples 2010 West 89 76 13 green Oranges 2008 East 96 81 15 NA Bananas 2008 East 85 76 9 yellow Oranges 2009 East 93 80 13 NA Bananas 2009 East 94 78 16 yellow Oranges 2010 East 98 91 7 NA Bananas 2010 East 81 71 10 yellow Hatena NA NA NA A NA blue Fruit Color Apples green Bananas yellow Hatena blue C Fruit Year Location Sales Expenses Profit Color Apples 2008 West 98 78 20 green Apples 2009 West 111 79 32 green Apples 2010 West 89 76 13 green Bananas 2008 East 85 76 9 yellow Bananas 2009 East 94 78 16 yellow Bananas 2010 East 81 71 10 yellow Fruit
  • 33. 2.データを加工する {dplyr} +α • データを結合する Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 cbind(Fruits1, Fruits2) Fruit Year Location Sales Expenses Profit Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 Fruits1 <- Fruits[1:3,] Fruits2 <- Fruits[c(4:6),] Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Fruit Year Location Sales Expenses Profit Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13 rbind(Fruits1, Fruits2) Fruit Year Location Sales Expenses Profit Apples 2008 West 98 78 20 Apples 2009 West 111 79 32 Apples 2010 West 89 76 13 Fruit Year Location Sales Expenses Profit Oranges 2008 East 96 81 15 Bananas 2008 East 85 76 9 Oranges 2009 East 93 80 13
  • 34. 3.データを可視化する データの可視化… • すべての基本: plot • 少し凝ったグラフ: ggplot • インタラクティブなグラフ: googleVis等 • その他(地図、3D…)
  • 35. 3.データを可視化する • plot関数 plot(x, y, …) plot(cars, main = "練習", xlab = "スピード", ylab = "距離", col = "blue") speed dist 4 2 4 10 7 4 7 22 8 16 9 10 10 18 10 26 10 34 11 17 11 28 12 14 12 20 … … cars
  • 36. 3.データを可視化する • plot関数 plot(x, y, …) plot(cars, main = "練習", xlab = "スピード", ylab = "距離", col = "blue") lines(cars, col=“red”) #折れ線の追加 speed dist 4 2 4 10 7 4 7 22 8 16 9 10 10 18 10 26 10 34 11 17 11 28 12 14 12 20 … … cars
  • 37. 3.データを可視化する • plot関数 plot(x, y, …) plot(cars, main = "練習", xlab = "スピード", ylab = "距離", col = "blue“, type = “b”) speed dist 4 2 4 10 7 4 7 22 8 16 9 10 10 18 10 26 10 34 11 17 11 28 12 14 12 20 … … cars
  • 38. 3.データを可視化する • plot関数 plot(x, y, …) plot(cars, main = "練習", xlab = "スピード", ylab = "距離", col = "blue“, type = “l”) speed dist 4 2 4 10 7 4 7 22 8 16 9 10 10 18 10 26 10 34 11 17 11 28 12 14 12 20 … … cars
  • 39. 3.データを可視化する • plot関数 plot(x, y, …) plot(cars, main = "練習", xlab = "スピード", ylab = "距離", col = "blue“, pch = 19) speed dist 4 2 4 10 7 4 7 22 8 16 9 10 10 18 10 26 10 34 11 17 11 28 12 14 12 20 … … cars
  • 40. 3.データを可視化する ☕ ☕ ☕ plotの形状(pch) • pch: 数値の場合1~25、文字列の場合任意 par(mfrow=c(2, 1)) plot(1:26, pch=1:26) plot(1:26, pch=LETTERS) LETTERS = c(“A”, “B”, … “Z”) Yの値、Xのデフォルト値は 1:length(Y) 画面の分割: mfrow(m,n) … m×nに分割 余白が足りない ⇒ 余白の調整はpar(mar())
  • 41. 3.データを可視化する ☕ ☕ ☕ plot画面(graphics device)を閉じる • dev.off() 現在のデバイスを閉じる • graphics.off() 全てのデバイスを閉じる • Rstudio上でも可能 全てのデバイスを閉じる
  • 43. 3.データを可視化する ☕ ☕ ☕ プロットが重なる場合 (例) N(0, 10)に従う乱数を1000個作りプロットする set.seed(1) test <- rnorm(1000, 0, 10) plot(test, pch=19) • {scales} alphaを使い半透明にする library(scales) plot(test, pch=19, alpha(“black”, 0.2)) α値の指定 個数 μ σ 乱数を固定
  • 44. 3.データを可視化する • 少し凝ったグラフ {ggplot2} ggplot(data, aes(x, y)) + geom_... • aes aesthentics(審美属性)。x, y, 色,サイズ • geom_ プロットの形式 geom_line, geom_points, geom_histogram等 • + ggplotでは+で重ね描きする (例) irisデータで密度推定 ggplot (iris, aes (x = Sepal.Length, y = Sepal.Width, colour = Species)) + stat_density2d ()
  • 45. 3.データを可視化する • 少し凝ったグラフ {ggplot2} その他の例 ggplot(iris, aes(x=Sepal.Length, fill=Species)) + geom_density(position='identity', alpha=.3) ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point(aes(color = Species), size = 2.5)
  • 46. 3.データを可視化する ☕ ☕ ☕ ggplotの便利さ データ加工と可視化を同時に行う ggplot(FruitsEdited, aes(Year, val)) + geom_line() + facet_grid(Fruit~var) facet_grid(y~x)により デバイス(画面)を分割し (x, y)に該当するグラフを描画する。 このときx軸、y軸は自動で統一される。 Fruit Year Location var val Apples 2008 West Sales 98 Apples 2009 West Sales 111 Apples 2010 West Sales 89 Oranges 2008 East Sales 96 Bananas 2008 East Sales 85 Oranges 2009 East Sales 93 Bananas 2009 East Sales 94 Oranges 2010 East Sales 98 Bananas 2010 East Sales 81 Apples 2008 West Expenses 78 Apples 2009 West Expenses 79 Apples 2010 West Expenses 76 Oranges 2008 East Expenses 81 Bananas 2008 East Expenses 76 Oranges 2009 East Expenses 80 Bananas 2009 East Expenses 78 Oranges 2010 East Expenses 91 Bananas 2010 East Expenses 71 Apples 2008 West Profit 20 Apples 2009 West Profit 32 Apples 2010 West Profit 13 Oranges 2008 East Profit 15 Bananas 2008 East Profit 9 Oranges 2009 East Profit 13 Bananas 2009 East Profit 16 Oranges 2010 East Profit 7 Bananas 2010 East Profit 10 FruitsEdited 自動で振り分けてくれる 軸も統一されている
  • 47. 3.データを可視化する • インタラクティブなグラフ {googleVis} M <- gvisMotionChart(Fruits, "Fruit", "Year", options=list(state='{"showTrails":false};')) plot(M)
  • 48. 3.データを可視化する • インタラクティブなグラフ {googleVis} M <- gvisMotionChart(Fruits, “Fruit”, “Year”, options=list(state='{"showTrails":false};')) plot(M)