r4ds 12 Visualising distributions 分布の可視化

library(dplyr)
library(tidyverse)

# 分布の可視化
# カテゴリカル変数では棒グラフを使う
ggplot(data = diamonds)+geom_bar(mapping = aes(x = cut))

# カテゴリカル変数の計量
diamonds %>% count(cut)

# 連続変数はヒストグラムを使う
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = carat), binwidth = 0.5)

# 度数分布表
diamonds %>%
count(cut_width(carat, 0.5))

# 3カラット以下に絞って、幅を0.1に狭くする
smaller <- diamonds %>%
filter(carat < 3)

ggplot(data = smaller, mapping = aes(x = carat)) +
geom_histogram(binwidth = 0.1)

# 複数のヒストグラムを1つに重ねる
ggplot(data = smaller, mapping = aes(x = carat, colour = cut)) +
geom_freqpoly(binwidth = 0.1)

# クラスターの例
# 細かくすると整数値が多い
ggplot(data = smaller, mapping = aes(x = carat)) +
geom_histogram(binwidth = 0.01)
# イエローストーンの間欠泉噴出時間
ggplot(data = faithful, mapping = aes(x = eruptions)) +
geom_histogram(binwidth = 0.25)

# 外れ値の例
ggplot(diamonds) +
geom_histogram(mapping = aes(x = y), binwidth = 0.5)
# 拡大する
ggplot(diamonds) +
geom_histogram(mapping = aes(x = y), binwidth = 0.5) +
coord_cartesian(ylim = c(0, 50))
# さらに詳しく調べる
unusual <- diamonds %>%
filter(y < 3 | y > 20) %>%
select(price, x, y, z) %>%
arrange(y)
unusual

外れ値がある場合
外れ値がある場合とない場合で分析を繰り返すのが良い。
結果に与える影響が最小限で、外れ値のある理由がわからないのなら欠損値として扱うのが妥当。
結果に明らかな影響があるのならば、正当な理由なく外れ値を外すわけにはいかない。
原因が何なのか明らかにして、削除したことをドキュメントにして開示する必要がある。

Follow me!