[R语言] 探索性数据分析 《R for data science》 3

《R for Data Science》第七章 Exploratory Data Analysis 啃书知识点积累

参考书籍

  1. 《R for data science》
  2. 《R数据科学》

“There are no routine statistical questions, only questionable statistical routines.” — Sir David Cox
“Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise.” — John Tukey

变动

- 连续变量等宽分箱并统计区间数

A variable is continuous if it can take any of an infinite set of ordered values. Numbers and date-times are two examples of continuous variables.

diamonds %>%
  count(cut_width(carat, 0.5))
# # A tibble: 11 x 2
# `cut_width(carat, 0.5)`     n
# <fct>                   <int>
# 1 [-0.25,0.25]              785
# 2 (0.25,0.75]             29498
# 3 (0.75,1.25]             15977
# 4 (1.25,1.75]              5313
# 5 (1.75,2.25]              2002
# 6 (2.25,2.75]               322
# 7 (2.75,3.25]                32
# 8 (3.25,3.75]                 5
# 9 (3.75,4.25]                 4
# 10 (4.25,4.75]                 1
# 11 (4.75,5.25]                 1

- 可视化

# 直方图geom_histogram
smaller <- diamonds %>%
   filter(carat < 3)
ggplot(data = smaller, mapping = aes(x = carat)) +
   # binwidth设置分箱宽度
   geom_histogram(binwidth = 0.1)

# 频率折线图geom_freqpoly
ggplot(data = smaller, mapping = aes(x = carat, color = cut)) +
   geom_freqpoly(binwidth = 0.1)

- 加强对异常值的观测

When you have a lot of data, outliers are sometimes difficult to see in a histogram.

  1. 分析变量分布
  2. coord_cartesian() 函数拓宽坐标轴刻度
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)) # 也可以调整xlim
# 会忽略溢出坐标轴范围的那些数据

缺失值

- 处理异常值

If you’ve encountered unusual values in your dataset, and simply want to move on to the rest of your analysis, you have two options.

  1. Drop the entire row with the strange values
diamonds2 <- diamonds %>%
  filter(between(y, 3, 20))
  1. replacing the unusual values with missing values (better)
diamonds2 <- diamonds %>%
  mutate(y = ifelse(y < 3 | y > 20, NA, y))

- ggplot2绘图中含有NA

Like R, ggplot2 subscribes to the philosophy that missing values should never silently go missing.

# 会自动忽略NA但有警告
ggplot(data = diamonds2, mapping = aes(x = x, y = y)) +
  geom_point()
#> #> Warning: Removed 9 rows containing missing values
#> (geom_point).

# 用na.rm = TRUE可以忽略NA
ggplot(data = diamonds2, mapping = aes(x = x, y = y)) +
  geom_point(na.rm = TRUE)

相关变动

Covariation is the tendency for the values of two or more variables to vary together in a related way

分类变量 vs 连续变量

- 密度

多组比较,如果组间数量差距较大,可以用密度对计数标化

To make the comparison easier we need to swap what is displayed on the y-axis. Instead of displaying count, we’ll display density, which is the count standardised so that the area under each frequency polygon is one.

library(patchwork) # 拼图包
library(RColorBrewer) # 配色包

display.brewer.all()
Set1 <- brewer.pal(name = "Set1",n=9)[1:5]

p1 <- ggplot(data = diamonds, mapping = aes(x = price)) +
  geom_freqpoly(mapping = aes(color = cut), binwidth = 500)+
  scale_color_manual(values = Set1)

p2 <- ggplot(data = diamonds, mapping = aes(x = price, y = ..density..)) +
  geom_freqpoly(mapping = aes(color = cut), binwidth = 500) +
  scale_color_manual(values = Set1)

p1 + p2

- reorder() 重排序

p1 <- ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
  geom_boxplot()

p2 <- ggplot(data = mpg) +
  geom_boxplot(
    mapping = aes(
      # 按照中位数重新排序
      x = reorder(class, hwy, FUN = median),
      y = hwy
    )
  )

# 变量名较长或出于美观可颠倒坐标轴
p3 <- ggplot(data = mpg) +
  geom_boxplot(
    mapping = aes(
      x = reorder(class, hwy, FUN = median),
      y = hwy
    )
  ) +
  coord_flip()

p1 + p2 + p3

两个分类变量

# geom_count
p1 <- ggplot(data = diamonds) +
  geom_count(mapping = aes(x = cut, y = color))

# geom_tile
p2 <- diamonds %>%
  count(color, cut) %>%
  ggplot(mapping = aes(x = color, y = cut)) +
  geom_tile(mapping = aes(fill = n)) + 
  coord_flip()

p1 + p2
  • 组间数量差距较大,不易分析相互分布
# color在cut中的分布
p1 <- diamonds %>%
  count(cut, color) %>% 
  group_by(cut) %>% 
  mutate(prop = n / sum(n)) %>% 
  ggplot(mapping = aes(x = cut, y = color)) +
  geom_tile(mapping = aes(fill = prop))


# cut在color中的分布
p2 <- diamonds %>%
  count(color, cut) %>% 
  group_by(color) %>% 
  mutate(prop = n / sum(n)) %>% 
  ggplot(mapping = aes(x = color, y = cut)) +
  geom_tile(mapping = aes(fill = prop))

p1 + p2
  • 利用因子确定分类变量
flights %>% 
  filter(!is.na(dep_delay)) %>% 
  group_by(month, dest) %>% 
  summarize(delay_mean = mean(dep_delay)) %>% 
  group_by(dest) %>% 
  filter(n() == 12) %>%  # 过滤出一年就有数据的目的地
  ungroup() %>% 
  ggplot(aes(x = factor(month), 
             # 重新排序 
             y = reorder(dest, delay_mean))) + 
  geom_tile(aes(fill = delay_mean)) + 
  xlab('Month') + 
  ylab('Destination')

更多内容见:[R语言] 与ggplot2相关有趣的包

两个连续变量

  • overplot 过绘制的解决
  1. 使用 alpha 图形属性添加透明度(数据量过大则不适用)
p1 <- ggplot(data = diamonds) +
  geom_point(mapping = aes(x = carat, y = price))


p2 <- ggplot(data = diamonds) +
  geom_point(mapping = aes(x = carat, y = price),
             alpha = 1 / 100)

p1 + p2
  1. 分箱
    (1) 二维分箱

geom_bin2d() 创建长方形分箱
geom_hex() 创建六边形分箱

p1 <- ggplot(diamonds) +
  geom_bin2d(mapping = aes(x = carat, y = price))

library(hexbin)
p2 <- ggplot(diamonds) +
  geom_hex(mapping = aes(x = carat, y = price))

p1 + p2

(2) 对一个连续变量分箱

By default, boxplots look roughly the same (apart from number of outliers) regardless of how many observations there are, so it’s difficult to tell that each boxplot summarises a different number of points.

p1 <- diamonds %>%
  filter(carat <= 2.8) %>% 
  ggplot(aes(x = carat, y = price)) +
  geom_boxplot(aes(group = cut_width(carat, 0.1)))

# varwidth让观测数和箱宽正相关
p2 <- diamonds %>%
  filter(carat <= 2.8) %>% 
  ggplot(aes(x = carat, y = price)) +
  geom_boxplot(aes(group = cut_width(carat, 0.1)),varwidth = T)

p1 / p2

cut_number()近似反映分箱内的数据数

ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
    geom_boxplot(mapping = aes(group = cut_number(carat, 20)))

模型和模式

Patterns provide one of the most useful tools for data scientists because they reveal covariation. If you think of variation as a phenomenon that creates uncertainty, covariation is a phenomenon that reduces it. If two variables covary, you can use the values of one variable to make better predictions about the values of the second. If the covariation is due to a causal relationship (a special case), then you can use the value of one variable to control the value of the second.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,924评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,902评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,716评论 0 239
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,783评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,166评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,510评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,784评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,476评论 0 196
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,196评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,459评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,978评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,321评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,964评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,046评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,803评论 0 193
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,530评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,420评论 2 265

推荐阅读更多精彩内容