Course 7 - Data Analysis with R Programming

簡介

This course is the seventh course in the Google Data Analytics Certificate. In this course, you’ll learn about the programming language known as R. You’ll find out how to use RStudio, the environment that allows you to work with R, and the software applications and tools that are unique to R, such as R packages. You’ll discover how R lets you clean, organize, analyze, visualize, and report data in new and more powerful ways.

章節大綱

  1. Programming and data analytics
    了解 R 和 RStudio。
  2. Programming using RStudio
    了解 R 語言中資料型態,並且學習套件如何安裝以及使用。
  3. Working with data in R
    學習利用 R 語言中的函數幫助篩選、排序資料,並且操作 data frames。
  4. More about visualizations, aesthetics, and annotations
    學習使用 ggplot2 建立圖表並且匯出。
  5. Documentation and reports
    學習使用 R Markdown 建立動態文檔。

內容筆記

Module 2 - Programming using RStudio

vectors

一組相同類型的資料元素

  1. 建立
1
2
3
4
c(2.5, 48.5, 101.5)
c(1L, 5L, 15L) #如果內容是整數,要在後面加上 L
c(“Sara” , “Lisa” , “Anna”)
c(TRUE, FALSE, TRUE)
  1. 命名
1
2
x <- c(1, 3, 5)
names(x) <- c("a", "b", "c")

list

可以包含各種類型的資料元素

1
2
list("a", 1L, 1.5, TRUE)
list(list(list(1 , 3, 5)))

matrices

二維矩陣,nrowncol 用於控制列和行的個數

1
2
matrix(c(3:8), nrow = 2)
matrix(c(3:8), ncol = 2)

Data frames

二維資料格式,有以下特點:

  1. 可以包含各種類型的資料。
  2. 每個單元格只有一個元素。
  3. 每個欄位都需要被命名。
  4. 每欄只包含相同類型的資料。
1
data.frame(x = c(1, 2, 3) , y = c(1.5, 5.5, 7.5))

Pipe

%>% 運算子可以用於連接兩個函數,將前面函數的輸出作為下一個函數的輸入使用,可以讓編寫程式更為省力,並且增加易讀性。

範例:

1
2
3
onlineta_city_hotels_v2 <- hotel_bookings %>%
filter(hotel=="City Hotel") %>%
filter(market_segment=="Online TA")

hotel_bookings 作為輸入放到第一個 filter 之後的結果再次作為輸入放入第二個 filter 中,最後存入 onlineta_city_hotels_v2

lubridate 套件

包含在 tidyverse 套件之中,使用前必須先安裝並且引入,主要是與時間、日期操有關的套件。

1
2
3
install.packages("tidyverse")
library(tidyverse)
library(lubridate)

時間資料類型:

  • date (“2016-08-16”)
  • time (“20:11:59 UTC")
  • date-time (“2018-03-31 18:15:48 UTC”)

相關函數:

  • today() 返回當前日期
  • now() 返回當前時間 (包含日期)
  1. 轉換為 date
1
2
3
ymd("2021-01-20")
mdy("January 20th, 2021")
ymd(20210120)
  1. 轉換為 date-time
1
2
ymd_hms("2021-01-20 20:11:59")
mdy_hm("01/20/2021 08:01")
  1. date-time 轉換為 date
1
as_date()

檔案操作

  1. 建立
1
2
3
file.create("new_text_file.txt") 
file.create("new_word_file.docx")
file.create("new_csv_file.csv")
  1. 複製
1
file.copy("new_text_file.txt", "destination_folder")
  1. 刪除
1
unlink("some_.file.csv")

Module 3 - Working with data in R

Data frames 操作-檢視

  1. head(data)
    顯示前六列資料。

  2. str(data)
    逐欄顯示資料的內部結構。

  3. colnames(data)
    列出各欄的名稱。

Data frames 清理

  1. clean_names(data, case)
    將欄位名稱改為特定格式,包含 “snake”, “lower_camel”…。

  2. rename(data, …), rename_with(data, case, …)
    重新命名欄位,rename_withcase 可以選擇 tolower 或是 toupper 將欄位名稱轉換為小寫或大寫,也可以指定轉換某些欄位。

  3. drop_na(data)
    清除包含缺失值的列。

Data frames 摘要

  1. glimpse(data)
    快速摘要資料集內容。

  2. skim_without_charts(data)
    全面的資料集摘要。

Data frames 篩選與排序

  1. select(data, …)
    篩選出要顯示的欄位 (與 SQL 中的類似)。

  2. filter(data, …)
    篩選符合特定條件的列。

  3. arrange(data, …)
    根據給定的欄位排序,預設為升序排列,如果要改為降序則要改為 desc(col),缺失值會被排在最後。

  4. group_by(data, …), summarize(data, …)
    group_by 可以根據給予的欄位進行分組,通常會配合 summarize 使用,summarize 可以將整個表格整理為單一個列,底下以統計各班級平均身高為例,以班級進行分組後,使用 mean() 函數計算平均身高。

1
2
summarize(data, class, avg_height = mean(height,na.rm = TRUE))
# na.rm 代表計算平均時忽略缺失值

Data frames 其他操作

  1. separate(data, col, into, sep)
    將一欄的數據拆分成多個欄位,into 代表新的欄位名稱,sep 代表分隔符。

  2. unite(data, col, …, sep)
    將多個欄位的資料透過分隔符合併為一欄,col 為新欄位名稱,sep 代表分隔符。

  3. mutate(data, …)
    對原有欄位進行操作,並將結果儲存到新欄位,以單位轉換為例:

1
2
mutate(data, height_cm = height * 100)
# 將原本的身高 (單位為公尺) 乘以 100 之後儲存到新欄位 height_cm

Tibbles

Tibbles 類似 Data frames 的進階版本,每次只會顯示資料的前十列,包含在 tidyverse 庫中,可以使用 as_tibble() 將 Data frames 轉換為 Tibbles。

Module 4 - More about visualizations, aesthetics, and annotations

Aesthetics

與圖表的視覺效果相關,包含大小、形狀、顏色等。

範例:

1
2
ggplot(data = penguins)+
geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species))

aes 中的 x,y 代表 x 軸和 y 軸對應的欄位,color 代表了點的顏色,在這裡是以不同的族群作為顏色區別。

其他可以使用的變數包含 shape, size, alpha (透明度), … 等。

Geom

與圖表的類型以及幾何物件相關,可以透過 + 符號連接以疊加多個圖表,以下舉例幾個常用的圖表類型:

  • geom_point 散佈圖
  • geom_jitter 抖動散佈圖 (當有資料點重複時,會產生隨機偏移)
  • geom_bar 長條圖
  • geom_line 折線圖
  • geom_smooth 趨勢線

Facets

將資料分群展示。

  1. facet_wrap(~col) 以單一欄位作為分類 (不會顯示空表格)
1
2
3
ggplot(data = hotel_bookings) +
geom_bar(mapping = aes(x = distribution_channel)) +
facet_wrap(~deposit_type)

deposit_type 進行分類,產生多個圖表,下圖是產生結果:

  1. facet_grid(row ~ col) 以兩個欄位做組合分類 (會顯示空表格)
1
2
3
ggplot(data = hotel_bookings) +
geom_bar(mapping = aes(x = distribution_channel)) +
facet_grid(~deposit_type~market_segment)

deposit_type 作為列,market_segment 作為欄進行分類,產生多個圖表,下圖是產生結果:

Lable and annotations

圖表的標籤以及其他文字。

1
2
3
4
ggplot(data = hotel_bookings) +
geom_bar(mapping = aes(x = market_segment)) +
facet_wrap(~hotel) +
labs(title="Comparison of market segments by hotel type for hotel bookings")

labs 之中加上 title 代表標題名稱,以下列舉其他可以加上的文字:

  • subtitle 子標題,位在標題下方
  • caption 字幕,位在圖表右下方
  • x, y 座標軸名稱,位在座標軸旁

除此之外也可以使用 annotate() 函數,在指定的位置上加上文字。

圖表儲存

要儲存產生的圖表可以使用 ggsave() 函數,默認會儲存最後一個生成的圖表,可以在函數中指定檔案名稱、大小以及解析度等等細節。

詞彙

  1. Aesthetic ®(美學): A visual property of an object in a plot.
  2. Nested (嵌套、巢狀): Code that performs a particular function and is containe d within code that performs a broader function.
  3. Tidyverse ®: A system of packages in R with a common design philosophy for data manipulation, exploration, and visualization.