Tidyverse:R 語言學習之旅的新起點

新興的學習模式(tidyverse first)

Yao-Jen Kuo
數聚點文摘
7 min readNov 21, 2017

--

Photo via Visualhunt.com

學習 R 語言的傳統路徑(base R first)多是從變數類型、資料結構、流程控制、迴圈與自訂函數,也就是以 R 程式設計作為起點,接著依照資料處理、視覺化、統計與機器學習等應用偏好延續下一個學習的旅程;由 tidyverse 作為起點的路徑則是近年新興的學習模式(tidyverse first),理念是在一開始先不談 [][[]]$ 流程控制與迴圈等內容,而從 dplyr 的函數應用開頭,目的是在最短時間讓初學者切入資料處理與視覺化的應用,讓 R 語言能夠很快地在課業、研究或者工作派上用場。

Tidyverse 究竟是什麼?它是由 RStudio 選出多個資料科學應用套件的集合,只要使用者暸解呼叫函數與 pipe 運算子 %>% 就能夠進行相當實用的資料處理與視覺化,這些應用套件包含:

  • 視覺化文法的王者 ggplot2
  • 資料處理的利器 dplyr
  • 長寬表格轉換的專家 tidyr
  • 資料載入的 readr
  • 消弭迴圈的加速器 purrr
  • 強化資料框的 tibble
tidyverse 的成員

Stack Overflow 的資料科學家 David Robinson 在 DataCamp 開設了 Introduction to the Tidyverse 課程,課程時數約四小時,練習完這個課程使用者將會獲得透過 dplyr 與 ggplot2 進行資料處理與視覺化的能力。

貫穿整個課程所使用的資料叫做 gapminder。Gapminder 是瑞典的非營利組織致力於提供簡單易懂的資料與視覺化讓國家之間的差距能夠讓大家看見,最著名的其中一位創辦人是 Hans Rosling,他在 2006 年的 TED 演講 “The best statistics you’ve never seen” 讓我們對近兩百年全球的國家發展有清晰的暸解。

Hans Rosling’s 200 Countries, 200 Years, 4 Minutes — The Joy of Stats — BBC Four@YouTube

我們只要在 R 語言載入 gapminder 套件能夠獲得這個資料的精簡版,它有 1704 個觀測值、6 個變數(country、continent、year、lifeExp、pop 與 gdpPercap)。

# install.packages("gapminder")
library(gapminder)
dim(gapminder)
head(gapminder)
gapminder 資料的外觀

完成練習之後,使用者將可以熟悉結合 pipe 運算子與 dplyr 做出類 SQL 查詢的資料處理:

# install.packages(c("tidyverse", "gapminder"))
library(tidyverse)
library(gapminder)
gapminder %>%
group_by(continent, year) %>%
summarize(medianLifeExp = median(lifeExp), maxGdpPercap = max(gdpPercap))
結合 pipe 運算子與 dplyr 的各種函數

以及熟悉 ggplot2 繪圖文法畫出氣泡圖:

# install.packages(c("tidyverse", "gapminder"))
library(tidyverse)
library(gapminder)
gapminder_1952 <- gapminder %>%
filter(year == 1952)
ggplot(gapminder_1952, aes(x = pop, y = lifeExp, color = continent, size = gdpPercap)) +
geom_point() +
scale_x_log10() +
theme_minimal()
使用 ggplot2 畫出氣泡圖

完成 Introduction to the Tidyverse 課程之後,David Robinson 也推薦了幾個DataCamp 的進階課程作為使用者的下一站,像是 Data Visualization with ggplot2、Data Manipulation with dplyr、Importing and cleaning data 與 Exploratory Data Analysis in R: Case Study。

我認為讓初學者從 tidyverse 切入是一個值得嘗試的教學方式,特別是在工作坊、講座或者短時間的課程;假如使用者計畫在未來會需要使用 R 語言完成更細膩的需求時,再分配較充足的時間學習 base R。

如果您喜歡這篇文章,請多按下方的「拍手」圖像幾次、分享到社群網站、成為我們的贊助者以及訂閱 DataInPoint 的新文章!

--

--