0%

R 語言教學入門|從變數賦值到資料型別

R 語言誕生於1993年,由兩位統計學家 George R. Ihaka 和 Robert C. Gentleman 在奧克蘭大學所開發,從命名簡單取自兩位創始人名字首字母便可看出,R 語言就是一個極簡且具有實用主義精神的程式語言。

目前幾乎全臺灣各大社會科學領域科系只要有開設統計相關課程,除了傳統的 SPSS、SAS 與 STATA 外,最常被使用的就是 R 語言了。作為一套統計語言,最初只在統計相關領域內流行,但隨著大數據時代來臨,R 語言專為數據分析設計的特性便備受青睞。R 語言的運算速度雖說不及Python,但R在統計模型和數據可視化方面仍獨具優勢。從統計教室到科技巨頭的資料科學部門,R已成為數據分析不可或缺的利器。

R 語言的基礎:賦值(Assign Values)

日常生活中,各種繁雜的資訊圍繞在我們身邊,有時需要記事本或是記事軟體等工具協助記憶這些資訊,如果沒有這些工具儲存如此複雜與繁瑣的資訊,僅憑腦力很難記住所有內容,且很容易出錯。

電腦也跟人一樣,需要把龐大的資訊用靈巧的方式記錄下來,「賦值」(assign value)則可以被理解為記錄下來的過程,並且可以給資料取名(變數名稱),在需要時就可以叫出來使用。這個過程就像是你在記事本上寫下「小明的電話:0912-345-678」,之後只需要翻到這一頁,就能找到小明的電話號碼。

舉例而言,假設小宋的身高是 183 公分,體重 70 公斤。如果我想分別儲存這兩個數值到 heightweight,可以這麼做:

1
2
height <- 183
weight <- 70

可以注意到,在變數與值之間存在一個箭頭 <- 符號,該符號即是 R 語言中的賦值符號,而不是其他程式語言常用的 =(雖然 = 在 R 中也可以使用)。這個左箭頭符號形象化地表示:將右邊的值「放入」左邊的變數中儲存。

當我們執行 height <- 183 這行程式碼後,R 在電腦記憶體中就建立了一個名為 height 的空間,並在此空間存入 數字 183,之後便可以使用這個變數名稱來取得或是修改這個值。

使用變數:印出變數的值

至於說如何使用變數,先從一個非常簡單的例子開始,就是「印出」變數。印出變數很直觀地來說,就是將變數所儲存的值印出來。賦值是人類向電腦說話的過程,要求電腦儲存變數,而印出或是顯示則是電腦向人類說話。在 R 語言中,使用 print() 便可以將變數印出,具體操作如下:

1
2
print(height) # 印出身高
print(weight) # 印出體重
[1] 183
[1] 70

使用變數:修改變數的值

上面也提到,變數空間所存放的值是可以被修改的(modified),我們只需重新操作一次賦值的動作,即可將變數所儲存的值修改。

1
2
3
4
5
height <- 170
print(height) # 印出身高

height <- 160
print(height) # 印出身高
[1] 170
[1] 160

列出變數與刪除變數

當在 R 語言中進行了一連串的資料儲存後,可能會好奇:目前記憶體裡到底有哪些變數已經被建立了?這時,就可以使用 ls() 這個指令來列出目前工作環境中所有變數的名稱。

1
ls()
  1. 'a'
  2. 'age'
  3. 'course'
  4. 'edu'
  5. 'flag'
  6. 'gender'
  7. 'group'
  8. 'has_data'
  9. 'height'
  10. 'is_student'
  11. 'name'
  12. 'num'
  13. 'school'
  14. 'score'
  15. 'weight'
  16. 'x'
  17. 'y'
  18. 'z'

假設你之前建立過以下幾個變數:

1
2
height <- 183
weight <- 70

執行 ls() 之後,R 會回傳:

1
[1] "height" "name" "weight"

這就像打開電腦桌面或是資料夾一樣,能看到目前有哪些資料已經儲存在裡頭,方便我們整理與管理。

那如果你發現某些變數已經不再需要,為了讓空間更清爽,或是避免變數名稱衝突,就可以使用 rm() 來刪除不需要的變數。比如說:

1
rm(height)

這樣就會把名為 height 的變數從記憶體中移除。若要一次刪除多個變數,也可以這樣寫:

1
rm(height, weight)

另外,如果你想要一口氣清空所有變數,可以搭配 ls() 一起使用:

1
rm(list = ls())

這行程式碼會先把所有變數的名字列出來,再把這些變數一次交給 rm() 去刪除,讓目前的工作環境恢復成一個「乾淨的白紙」。需要注意的是,變數一旦被 rm() 刪除,就無法復原,除非你事先儲存過或重新執行建立變數的程式碼。因此在執行刪除操作時,請務必確認是不是真的不再需要那些變數了

變數命名規則

假設有天你在記事本上寫了一條這樣的內容:

adsadadfd 164

然後一個月之後回來看,相信你的反應肯定會跟下面這張圖一樣

這就是為什麼我們要好好地「命名變數」。畢竟電腦不像人類能夠憑上下文猜意思,它只能忠實地執行你給的名字與指令。如果你用了毫無意義或看不出邏輯的變數名稱,不但日後維護困難,也容易讓協作的組員或同事看得一頭霧水。

在 R 語言中,變數命名需要遵守幾個基本原則:

  1. 只能以字母或「.」開頭,不能以數字起頭,例如 1height 就會報錯,而 height1 則是合法的命名。
  2. 只能包含字母、數字、「.」與底線 _,不能包含空格或特殊符號。
  3. 區分大小寫,Heightheight 是兩個不同的變數。
  4. 避免使用 R 保留字(例如 ifelseforfunction 等),雖然技術上可以加上反引號(例如 `if`),但會造成程式難以閱讀與維護。
  5. 盡量取具有語意的變數名,讓閱讀程式碼時像是在讀一段清楚的邏輯說明。例如 age_of_student 比起 aos 更容易讓人理解。

以命名風格來說,R 語言的使用者普遍偏好使用「小寫加底線」的命名方式,也就是蛇形命名法(snake case),像是 student_heightaverage_score。當然也有人會使用駝峰式命名(camel case),像是 studentHeight

總之,筆者認為變數命名不是一件小事,而是一種對程式碼負責任的態度。好的命名習慣,不但可以提升閱讀性,也能幫助未來的你或其他開發者得以更快速理解整體程式碼的邏輯與架構。畢竟寫程式不只是與電腦溝通,更是與未來的自己對話。

變數型別:資料的不同形式

在 R 語言中,變數就像是一個個小盒子,裡頭裝著我們想要儲存的資料。但並不是每個盒子裝的東西都一樣,有些盒子裝的是數字、有些是文字,有些甚至是一整列數據或是表格。為了讓電腦能正確地處理這些資料,我們需要了解變數型別(data type),也就是這些盒子裡的資料到底是什麼形式。

  • 數值型 (numeric) - 包含整數和小數
  • 字元型 (character) - 文字或字串
  • 邏輯型 (logical) - 布林值,即 TRUEFALSE
  • 複數型 (complex) - 數學中的複數
  • 整數型 (integer) - 明確指定為整數的數值
  • 因子型 (factor) - 分類變數

而在接下來的介紹中,我們會使用 class() 來顯示一個變數的型別,讓我們可以清楚地知道這個變數屬於哪一類,從而選擇正確的處理方式。就像是在收納之前先看清楚東西的性質,是書本、衣服還是餐具,才能放進對應的抽屜裡。透過確認型別,我們就能讓 R 準確地幫我們完成各種運算與分析任務。

數值(Numeric)

數值型別是 R 中最常見的資料型別,用來表示各種連續的數字。無論是身高、體重、溫度、收入或任何可以量化的資料,幾乎都會被視為數值。

1
2
3
4
5
6
7
x <- 3.14
print(x)
print(class(x))

y <- 100
print(x)
print(class(y))
[1] 3.14
[1] "numeric"
[1] 3.14
[1] "numeric"

即使你寫的是一個整數 100,R 仍會把它視為數值,除非你特別指定它為整數型別,這稍後會提到。

字串(Character)

當資料不是數字,而是「文字」的時候,就屬於字串型別(character)。例如姓名、地址、科系名稱、學校、縣市名稱等,都屬於字串資料。

1
2
3
4
5
6
7
name <- "小明"
print(name)
print(class(name))

school <- "國立臺灣大學"
print(school)
print(class(school))
[1] "小明"
[1] "character"
[1] "國立臺灣大學"
[1] "character"

字串資料在 R 中必須用雙引號(")或單引號(')包起來,否則 R 會以為你是在呼叫變數而不是輸入文字。

布林值 (Logical)

布林值(logical)是資料科學與邏輯運算中不可或缺的型別,只會有兩種可能的值:TRUEFALSE,分別代表「真」與「假」、「是」與「不是」。

1
2
3
4
5
6
7
is_student <- TRUE
print(is_student)
print(class(is_student))

has_data <- FALSE
print(has_data)
print(class(has_data))
[1] TRUE
[1] "logical"
[1] FALSE
[1] "logical"

R 中的布林值是全大寫 TRUEFALSE,雖然你可以用 TF 代替,但為了避免混淆,還是建議使用完整拼法

整數(Integer)

雖然我們在 R 中輸入 100,預設會是數值型別,但有時候我們想要明確定義資料是「整數」,可以在數字後面加上 L

1
2
3
a <- 100L
print(a)
print(class(a))
[1] 100
[1] "integer"

整數在資料處理時有時能節省記憶體,特別是在處理大量離散變數(如年齡、人數)時會使用。

複數(Complex)

R 也支援複數資料,雖然在一般的資料分析裡比較少用到,但在某些工程或數學應用中仍然重要,所以在這邊還是作簡單的介紹。例如我們定義一個複數 $z \in \mathbb{C}$ 為 $z = 3 + 2i$,其中 $i = \sqrt{-1}$。

1
2
3
z <- 3 + 2i
print(z)
print(class(z))
[1] 3+2i
[1] "complex"

因子(Factor)

在社會科學與統計分析中,最常見的一類資料就是類別資料(categorical data),像是性別(男、女)、年級(大一、大二、大三、大四)、地區(北部、中部、南部、東部)等等。這類資料乍看之下像是字串,但其實有明確的「分類結構」,這時候就可以用「因子」(factor)來表示。在迴歸分析或是做交叉表時,因子變數可以讓 R 正確處理類別型資料,而不是誤以為這些資料可以做數值運算。

使用 factor() 函數可以將一組文字轉換為因子型別,並且自動幫你識別有哪些不同的「層級」(levels),也就是固定幾種選項的文字資料。在底下的例子中,factor() 會掃描整個向量,找出有哪些不重複的值,然後建立層級,而 R 預設會根據字母順序來排序這些層級,所以「女」會排在「男」之前。

1
2
3
4
gender <- factor(c("男", "女", "女", "男"))
print(gender)
print(class(gender))
print(levels(gender)) # 印出層級
[1] 男 女 女 男
Levels: 女 男
[1] "factor"
[1] "女" "男"

至於為何是以「女」在「男」前面做排序,是因為 R 語言使用 Unicode 編碼系統將字符進行排序。在 Unicode 中,中文漢字根據其編碼值來排序,而不是根據中文字的拼音或筆劃。使用以下的小功能查詢「女」和「男」的 Unicode 編碼可以發現:

  • 「女」的 Unicode 編碼是 U+5973(十進位: 22899)
  • 「男」的 Unicode 編碼是 U+7537(十進位: 30007)

因為「女」的 Unicode 編碼值(22899)小於「男」的編碼值(30007),所以在 R 語言中使用 factor() 函數時,若未明確指定排序方式,R 會根據字符的 Unicode 編碼值自動進行排序,導致「女」會被排在「男」之前。因此這只是一個純粹的技術排序結果,與性別本身無關,僅僅反映了這些字符在 Unicode 編碼標準中的相對位置。

請輸入中文字:

轉換結果將在這裡顯示...

如果資料是有順序的(ordered),那麼我們可以試定順序性:有些類別變數是有「順序」的,例如教育程度(國中 < 高中 < 大學 < 研究所),這種情況下可以使用 ordered = TRUE 參數來建立有順序的因子。

1
2
3
4
5
6
7
edu <- factor(c("大學", "高中", "研究所", "高中"),
levels = c("國中", "高中", "大學", "研究所"),
ordered = TRUE)

print(edu)
print(class(edu))
print(levels(edu)) # 印出層級
[1] 大學   高中   研究所 高中  
Levels: 國中 < 高中 < 大學 < 研究所
[1] "ordered" "factor" 
[1] "國中"   "高中"   "大學"   "研究所"

如何檢查變數的型別?

當我們在 R 語言中建立或載入變數時,掌握每個變數的資料型別是非常重要的一步。因為 R 的函數與運算,往往會根據變數的型別來決定如何處理資料。例如:某些統計模型只能處理數值型資料,而某些分類分析則要求類別型資料。如果我們不清楚變數的型別,就很容易在分析過程中遇到錯誤、報錯訊息或是出現不合理的結果。

為了協助使用者更方便地檢查與判斷變數的型別,R 語言內建了一組非常實用的函數。這些函數可以分成兩類用途:取得變數的型別資訊以及判斷變數是否為特定型別

函數名稱 說明
class(x) 顯示變數 x 的「主要類別」,這是最常用來辨識型別的函數。
typeof(x) 顯示變數的底層儲存形式,比 class() 更技術性,可看出最底層記憶體型別。
is.numeric(x) 回傳 TRUEFALSE,用來判斷 x 是否為數值型變數(包含整數與小數)。
is.character(x) 判斷 x 是否為文字型(字串)變數。
is.logical(x) 判斷 x 是否為布林值(TRUE/FALSE)。
is.factor(x) 判斷 x 是否為因子(factor)。因子主要用來表示分類資料。

class(x):快速判斷變數是什麼

這是最常見也是最直覺的函數。class() 會告訴你這個變數在 R 中被歸類為哪一種資料型別,不過前面已經提過,在此便不多作贅述。不過 class() 的核心概念即是 R 幫你貼上的「資料型別標籤」,讓你在進行分析之前,先確定這些變數該怎麼使用。

typeof(x):深入了解變數的底層型別

雖然 class() 是我們最常用的函數,但它顯示的是變數的「表面型別」,也就是 R 認為這個變數是什麼。然而,有些時候我們需要知道變數的底層資料儲存方式,這時可以使用 typeof() 函數,目的是在處理記憶體改善或進階資料結構時會很有幫助。

1
2
3
x <- 42
print(class(x)) # R 儲儲存為數值型別
print(typeof(x)) # 底層儲存為浮點數
[1] "numeric"
[1] "double"

在這個例子中,我們看到 x 是數值型別,但底層實際上是 double,也就是雙精度浮點數。

is.numeric()is.character()is.logical():判斷型別用的布林函數

這些函數的功能非常直觀,就是檢查某個變數是否屬於某一個特定型別。如果是,就會回傳 TRUE;如果不是,則回傳 FALSE

這些函數在撰寫條件式或是做資料清理(data cleaning)時非常有用。例如你可以在資料前處理階段用 is.character() 篩選出所有字串欄位,再進一步轉換或處理。

1
2
3
4
5
6
7
8
9
10
11
score <- 85
print(score)
print(is.numeric(score))

course <- "資料分析"
print(course)
print(is.character(course))

flag <- TRUE
print(flag) # 此處印出的 TRUE 是 flag 儲存的值
print(is.logical(flag))
[1] 85
[1] TRUE
[1] "資料分析"
[1] TRUE
[1] TRUE
[1] TRUE

is.factor():辨別分類變數的好幫手

文章前面已經提到,在社會科學領域十分常遇到類別資料,我們可以用 is.factor() 來判斷它是否已經是因子型別,對於後續的統計模型十分重要,因為某些模型會根據是否為 factor 來套用不同處理邏輯。

1
2
group <- factor(c("A", "B", "A", "C"))
print(is.factor(group))
[1] TRUE

型別轉換:讓資料用對的形式說話

當每個變數被建立時,都會自動被賦予一個型別,這些型別就像是 R 對資料的「理解方式」,而我們在寫程式時,必須讓電腦能正確「理解」我們的資料。

但現實世界的資料,常常不會乖乖地照著我們希望的格式來。例如從 Excel 或 CSV 匯入的數字,可能會變成字串;問卷資料中的選項看起來是文字,但其實應該要當作類別資料來分析。這時候,我們就需要使用「型別轉換」的工具,讓資料以正確的形式存在於記憶體中。

函數名稱 說明
as.numeric() 轉換為數值型
as.integer() 轉換為整數型
as.character() 轉換為字串型(文字)
as.logical() 轉換為布林值(TRUE / FALSE)
as.factor() 轉換為因子型(分類變數)

實際範例

有時我們從外部資料讀進來的數字,其實是以字串儲存的。這在 CSV 或 Excel 特別常見,因為這些格式的欄位格式不總是固定。

1
2
3
4
5
age <- "25"
print(class(age))

age <- as.numeric(age)
print(class(age))
[1] "character"
[1] "numeric"

這樣我們就可以把 "25" 從純文字變成數字 25,並能進行加減乘除等運算。另一個例子是將字串轉換成類別資料,問卷資料最常見的欄位是像「性別」、「教育程度」、「滿意度」這類資料,表面看起來是字串,其實應該視為類別資料,這時就可以轉換成因子。

1
2
3
edu <- c("大學", "高中", "研究所", "高中")
edu <- as.factor(edu)
print(class(edu))
[1] "factor"

不是所有資料都能順利轉型

型別轉換雖然方便,但不是萬能的。首先,文字無法轉成數字:這種情況會產生警告,並將結果設為 NA(缺失值),代表 R 嘗試轉型失敗。

1
2
x <- "apple"
as.numeric(x)
Warning message:
"NAs introduced by coercion"

<NA>

另外一個則是布林值轉成數值,雖說這樣轉換是合法的,TRUE 被視為 1,FALSE 被視為 0。但在統計分析中必須小心,切勿讓模型誤以為這是數值大小的比較

1
2
3
4
5
x <- TRUE
print(as.numeric(x))

y <- FALSE
print(as.numeric(y))
[1] 1
[1] 0

運算子:資料處理的基本工具

在我們學會如何設定變數與了解變數型別之後,接下來就該學習如何操作這些變數。就像我們日常生活中需要計算費用、比較價格、判斷條件一樣,在 R 語言中,我們也需要各種運算子來處理和分析。運算子就像是數據分析的基本工具,讓我們能夠進行計算、比較與邏輯判斷,是從簡單報表到複雜模型所有操作的基礎。

在 R 語言中,運算子大致可以分為三大類:

  • 算術運算子 - 進行各種數學計算
  • 比較運算子 - 比較不同值之間的關係
  • 邏輯運算子 - 組合多個條件進行判斷

了解這些運算子不僅能幫助我們進行基本的資料處理,還能在資料篩選、條件式程式設計和統計分析中發揮重要作用。就像廚師需要切菜刀、炒菜鍋一樣,資料分析師需要熟練掌握各種運算子,才能靈活地處理各種資料分析問題。

算術運算子:數值的基本計算

算術運算子是最基本的運算工具,就像我們從小學開始學習的加減乘除一樣直觀。在 R 語言中,這些運算子的使用方式跟我們的數學習慣很接近,讓初學者能夠快速上手。

運算子 說明 範例 結果
+ 加法 5 + 3 8
- 減法 5 - 3 2
* 乘法 5 * 3 15
/ 除法 5 / 3 1.666667
^ 次方 5 ^ 3 125
%% 取餘數 5 %% 3 2
%/% 整數除法 5 %/% 3 1

讓我們用一些實際例子來看看這些運算子的使用:

1
2
3
4
5
6
7
8
# 基本加減乘除
a <- 10
b <- 3

print(a + b) # 加法
print(a - b) # 減法
print(a * b) # 乘法
print(a / b) # 除法 (會有小數)
[1] 13
[1] 7
[1] 30
[1] 3.333333

特別值得一提的是次方、取餘數與整數除法這三個運算子,它們在特定情境中特別有用:

1
2
3
4
5
6
7
8
# 次方運算 (5的3次方)
print(5 ^ 3)

# 取餘數 (10除以3的餘數)
print(10 %% 3)

# 整數除法 (10除以3的整數部分)
print(10 %/% 3)
[1] 125
[1] 1
[1] 3

在資料分析中,這些運算子可以幫助我們進行各種計算,例如:計算平均值、標準差、增長率、比例等等。尤其是 %%%/% 這兩個運算子,在處理時間數據(例如每週循環、每月循環)或是需要將連續數值分組時非常有用。

比較運算子:值之間的關係判斷

比較運算子用於比較兩個值之間的關係,結果永遠是布林值 TRUEFALSE。這些運算子在資料篩選、條件式程式設計中扮演著關鍵角色,讓我們能夠根據特定條件來處理資料。

運算子 說明 範例 結果
< 小於 5 < 3 FALSE
<= 小於等於 5 <= 5 TRUE
> 大於 5 > 3 TRUE
>= 大於等於 5 >= 6 FALSE
== 等於 5 == 5 TRUE
!= 不等於 5 != 3 TRUE

讓我們透過實際例子來理解這些比較運算子的用法:

1
2
3
4
5
6
7
8
9
x <- 7
y <- 5

print(x < y) # x 小於 y?
print(x <= y) # x 小於等於 y?
print(x > y) # x 大於 y?
print(x >= y) # x 大於等於 y?
print(x == y) # x 等於 y?
print(x != y) # x 不等於 y?
[1] FALSE
[1] FALSE
[1] TRUE
[1] TRUE
[1] FALSE
[1] TRUE

在實際的數據分析中,比較運算子通常用於:

  • 篩選符合條件的資料(例如:年齡大於 18 的樣本)
  • 建立分組變數(例如:依照成績高低分組)
  • 檢查資料是否符合預期(例如:確認沒有負數值)

比較運算子看似簡單,但它們是構建複雜條件和邏輯的基石,在資料清理與前處理階段尤其重要。

邏輯運算子:組合多個條件

當我們需要同時考慮多個條件時,就需要用到邏輯運算子。邏輯運算子能夠組合多個布林值(TRUEFALSE),產生新的布林結果,讓我們能夠表達更複雜的條件判斷。

運算子 說明 範例 結果
& 邏輯與 (AND) TRUE & FALSE FALSE
` ` 邏輯或 (OR) `TRUE
! 邏輯非 (NOT) !TRUE FALSE
&& 短路邏輯與 expr1 && expr2 只有當 expr1 為 TRUE 時才會評估 expr2
` ` 短路邏輯或

讓我們用幾個例子來理解這些邏輯運算子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
a <- TRUE
b <- FALSE

# 邏輯與:兩者皆為TRUE才會回傳TRUE
print(a & b)
print(TRUE & TRUE)

# 邏輯或:只要有一者為TRUE就會回傳TRUE
print(a | b)
print(FALSE | FALSE)

# 邏輯非:將布林值反轉
print(!a)
print(!b)
[1] FALSE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE

需要特別說明的是 &&&||| 的區別:

  • &| 是「向量化」的運算子,會對兩個向量的每個元素進行比較
  • &&|| 是「短路」運算子,只考慮向量的第一個元素,且在某些條件下不會評估第二個表達式
1
2
3
4
5
6
7
8
9
# 向量化運算
print(c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE))

# 短路運算
x <- 5
print((x > 0) && (log(x) > 0)) # 因為 x > 0 為 TRUE,才會計算 log(x) > 0

y <- -5
print((y > 0) && (log(y) > 0)) # 因為 y > 0 為 FALSE,不會計算 log(y) > 0,避免錯誤
[1]  TRUE FALSE FALSE


[1] TRUE
[1] FALSE

邏輯運算子在實際的資料分析中有許多應用:

  • 複雜的資料篩選(例如:年齡在 18-65 之間且收入大於 3 萬的樣本)
  • 條件式資料處理(例如:對不同群組套用不同的計算方法)
  • 異常值檢測(例如:找出超出正常範圍的數據點)

運算子的優先順序

就像數學計算有優先順序(先乘除後加減)一樣,R 語言中的運算子也有其優先順序,決定了複雜表達式的計算順序。

以下是 R 語言中運算子的優先順序(由高到低):

  1. ^ (次方)
  2. * / %% %/% (乘法、除法、取餘數、整數除法)
  3. + - (加法、減法)
  4. < <= > >= == != (比較運算子)
  5. ! (邏輯非)
  6. & (邏輯與)
  7. | (邏輯或)
  8. <- (賦值)

當表達式複雜時,為了避免混淆和潛在錯誤,建議使用括號 () 明確指定運算順序,這不只能讓程式碼更清晰易讀,也能避免因為優先順序問題導致的錯誤。

1
2
3
4
5
# 不使用括號,可能造成混淆
result <- 2 + 3 * 4 > 10 & 5 + 2 == 7

# 使用括號,更加清晰
result <- ((2 + (3 * 4)) > 10) & ((5 + 2) == 7)

使用套件

R 語言的世界中,套件(packages)就像是各種神奇的工具箱,為基礎的 R 語言增添各式各樣的功能。想像一下,如果說基礎的 R 語言是一間麻雀雖小但五臟俱全的工作室,那麼套件就是各種專業設備,讓這間工作室能夠升級成為全方位的工廠。無論是資料視覺化、機器學習、網頁爬蟲,還是地理空間分析,都有相對應的套件可以協助你完成任務。

什麼是 R 套件?

R 套件是由程式碼、資料與文件所組成的集合,提供特定功能或是解決特定領域的問題。如果我們把 R 語言比喻成一台基本的智慧型手機,那麼套件就像是各種 App,讓你的手機能夠做更多事情。套件通常包含:

  1. 函數(functions): 封裝好的程式碼片段,用來執行特定任務
  2. 資料集(datasets): 範例或實用的資料,方便學習與測試
  3. 文件(documentation): 使用說明與範例程式碼
  4. Vignettes: 詳細的使用指南,通常是一篇完整的教學文章

為什麼需要套件?

基礎的 R 安裝版本(也被稱為 Base R)已經包含了許多強大的功能,但對於特定領域的資料分析與統計需求,這些功能可能不夠專業或高效。即使是 R 語言的創始者們也無法預見所有可能的應用場景,更不用說為每一種應用開發完整的函數庫。這就是為什麼 R 社群創建了套件系統,讓各路專家們能夠開發並分享他們領域的專業工具,進而造就了 R 語言生態系統的繁榮跟多樣化。

舉例來說,如果你想要:

  • 製作精美的資料視覺化圖表 → ggplot2 套件
  • 進行文字探勘與自然語言處理 → tmtidytext 套件
  • 建構深度學習模型 → kerastensorflow 套件
  • 分析地理空間資料 → sfspleaflet 套件

所有這些功能都不在基礎 R 中,但透過套件系統,我們可以輕鬆地擴充 R 的能力,讓它成為一個幾乎無所不能的資料分析平台。

R 套件的生態系統

R 的套件系統由幾個主要部分組成:

  • CRAN (Comprehensive R Archive Network): R 語言的官方套件倉庫,目前擁有超過 19,000 個套件。
  • GitHub/GitLab: 許多最新或實驗性的套件會先在 GitHub 或 GitLab 上發布,等穩定後才上傳到 CRAN。
  • 私人或商業套件倉庫: 一些機構或公司會維護自己的套件倉庫,用於內部或商業用途。

CRAN 是最常用的套件來源,因為它提供了穩定、可靠且經過審查的套件,適合大多數人的需求。

安裝與管理套件

在開始使用套件前,我們需要先將它們安裝到我們的 R 環境中。就像在手機上下載 App 一樣,我們需要一些特定的指令來安裝、更新或移除套件。讓我們從最基本的安裝方法開始。

從 CRAN 安裝套件

CRAN 是安裝 R 套件最常見的方式,使用 install.packages() 函數即可:

1
2
3
4
5
# 安裝單一套件
install.packages("ggplot2")

# 同時安裝多個套件
install.packages(c("dplyr", "tidyr", "readr"))
The downloaded binary packages are in
	/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/downloaded_packages

The downloaded binary packages are in
	/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/downloaded_packages

這個指令會從 CRAN 伺服器下載最新版本的套件,並安裝到你的 R 環境中。如果套件依賴於其他套件,R 會自動安裝這些依賴套件,就像智慧型手機在下載某個 App 時,會一併下載它所需的框架一樣。

從 GitHub 安裝套件

有些套件尚未在 CRAN 上發布,或者 GitHub 上的版本有更新的功能,這時候我們可以直接從 GitHub 安裝:

1
2
3
4
5
# 先安裝 devtools 或 remotes 套件(如果尚未安裝)
install.packages("devtools")

# 從 GitHub 安裝套件
devtools::install_github("tidyverse/ggplot2")
The downloaded binary packages are in
	/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/downloaded_packages


Using GitHub PAT from the git credential store.

Downloading GitHub repo tidyverse/ggplot2@HEAD




-- R CMD build -----------------------------------------------------------------
* checking for file '/private/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T/RtmpypbpVp/remotes1847c3577c093/tidyverse-ggplot2-8b2a764/DESCRIPTION' ... OK
* preparing 'ggplot2':
* checking DESCRIPTION meta-information ... OK
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'ggplot2_3.5.1.9000.tar.gz'

devtools::install_github() 中的雙冒號 :: 表示「從 devtools 套件中呼叫 install_github 函數」,這個語法在後面會詳細介紹。在 GitHub 安裝指令中,"tidyverse/ggplot2" 指的是 GitHub 帳號/儲存庫名稱。

安裝特定版本的套件

有時候為了確保程式碼的穩定性,我們可能需要安裝特定版本的套件,若從 CRAN 安裝,使用 version == "版本號" 指定版本即可,若從 GitHub 安裝,則使用 ref 參數指定版本或分支。

1
2
3
4
5
# 從 CRAN 安裝特定版本
devtools::install_version("ggplot2", version = "3.3.0")

# 從 GitHub 安裝特定版本
devtools::install_github("tidyverse/ggplot2", ref = "v3.3.0")
Downloading package from url: https://cran.r-project.org/src/contrib/Archive/ggplot2/ggplot2_3.3.0.tar.gz



rlang  (1.1.4 -> 1.1.5 ) [CRAN]
cli    (3.6.3 -> 3.6.4 ) [CRAN]
pillar (1.9.0 -> 1.10.2) [CRAN]
R6     (2.5.1 -> 2.6.1 ) [CRAN]


Installing 4 packages: rlang, cli, pillar, R6

Warning message in i.p(...):
"installation of package '/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/remotes1847c67419376/ggplot2' had non-zero exit status"
Using GitHub PAT from the git credential store.

Downloading GitHub repo tidyverse/ggplot2@v3.3.0




-- R CMD build -----------------------------------------------------------------
* checking for file '/private/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T/RtmpypbpVp/remotes1847c184f2d66/tidyverse-ggplot2-625a03a/DESCRIPTION' ... OK
* preparing 'ggplot2':
* checking DESCRIPTION meta-information ... OK
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'ggplot2_3.3.0.tar.gz'



Warning message in i.p(...):
"installation of package '/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/file1847c762d9001/ggplot2_3.3.0.tar.gz' had non-zero exit status"

管理已安裝的套件

過一段時間後,我們可能需要查看、更新或移除已安裝的套件

1
2
3
4
5
6
7
8
9
10
11
# 查看已安裝的套件
installed.packages()

# 更新所有套件
update.packages()

# 更新特定套件
install.packages("ggplot2") # 重新安裝也會更新

# 移除套件
remove.packages("ggplot2")
A matrix: 279 x 16 of type chr
PackageLibPathVersionPriorityDependsImportsLinkingToSuggestsEnhancesLicenseLicense_is_FOSSLicense_restricts_useOS_typeMD5sumNeedsCompilationBuilt
AERAER /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.2-14 NA R (>= 3.0.0), car (>= 2.0-19), lmtest, sandwich (>= 2.4-0), survival (>= 2.37-5), zoostats, Formula (>= 0.2-0) NA boot, dynlm, effects, fGarch, forecast, foreign, ineq, KernSmooth, lattice, longmemo, MASS, mlogit, nlme, nnet, np, plm, pscl, quantreg, rgl, ROCR, rugarch, sampleSelection, scatterplot3d, strucchange, systemfit (>= 1.1-20), truncreg, tseries, urca, varsNA GPL-2 | GPL-3 NA NANANAno 4.4.1
ALSMALSM /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.2.0 NA R (>= 3.0.0), stats, graphics, leaps, SuppDists, car NA NA NA NA GPL-2 | GPL-3 NA NANANAno 4.4.2
BHBH /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.84.0-0 NA NA NA NA NA NA BSL-1.0 NA NANANAno 4.4.0
DBIDBI /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.2.3 NA methods, R (>= 3.0.0) NA NA arrow, blob, covr, DBItest, dbplyr, downlit, dplyr, glue, hms, knitr, magrittr, nanoarrow (>= 0.3.0.1), RMariaDB, rmarkdown, rprojroot, RSQLite (>= 1.1-2), testthat (>= 3.0.0), vctrs, xml2 NA LGPL (>= 2.1) NA NANANAno 4.4.0
DerivDeriv /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library4.1.6 NA NA methods NA testthat (>= 0.11.0) NA GPL (>= 3) NA NANANAno 4.4.1
FormulaFormula /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.2-5 NA R (>= 2.0.0), stats NA NA NA NA GPL-2 | GPL-3 NA NANANAno 4.4.0
IRdisplayIRdisplay /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.1 NA R (>= 3.0.1) methods, repr NA testthat, withr NA MIT + file LICENSE NA NANANAno 4.4.0
IRkernelIRkernel /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.3.2 NA R (>= 3.2.0) repr (>= 0.4.99), methods, evaluate (>= 0.10), IRdisplay (>= 0.3.0.9999), pbdZMQ (>= 0.2-1), crayon, jsonlite (>= 0.9.6), uuid, digestNA testthat, roxygen2 NA MIT + file LICENSE NA NANANAno 4.4.0
ISOcodesISOcodes /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library2024.02.12NA R (>= 3.5.0) NA NA NA NA GPL-2 NA NANANAno 4.4.0
KernSmoothKernSmooth /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library2.23-24 recommendedR (>= 2.5.0), stats NA NA MASS, carData NA Unlimited NA NANANAyes4.4.2
MASSMASS /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library7.3-61 recommendedR (>= 4.4.0), grDevices, graphics, stats, utils methods NA lattice, nlme, nnet, survival NA GPL-2 | GPL-3 NA NANANAyes4.4.2
MatrixMatrix /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.7-1 recommendedR (>= 4.4.0), methods grDevices, graphics, grid, lattice, stats, utils NA MASS, datasets, sfsmisc, tools SparseM, graph GPL (>= 2) | file LICENCE NA NANANAyes4.4.2
MatrixModelsMatrixModels /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.5-3 NA R (>= 3.6.0) stats, methods, Matrix (>= 1.6-0) NA NA NA GPL (>= 2) NA NANANAno 4.4.0
NLPNLP /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.3-2 NA R (>= 3.5.0) utils NA NA udpipe, spacyr, cleanNLPGPL-3 NA NANANAno 4.4.1
R.cacheR.cache /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.16.0 NA R (>= 2.14.0) utils, R.methodsS3 (>= 1.8.1), R.oo (>= 1.24.0), R.utils (>= 2.10.1), digest (>= 0.6.13) NA NA NA LGPL (>= 2.1) NA NANANAno 4.4.0
R.methodsS3R.methodsS3 /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.8.2 NA R (>= 2.13.0) utils NA codetools NA LGPL (>= 2.1) NA NANANAno 4.4.0
R.ooR.oo /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.27.0 NA R (>= 2.13.0), R.methodsS3 (>= 1.8.2) methods, utils NA tools NA LGPL (>= 2.1) NA NANANAno 4.4.1
R.utilsR.utils /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library2.12.3 NA R (>= 2.14.0), R.oo methods, utils, tools, R.methodsS3 NA datasets, digest (>= 0.6.10) NA LGPL (>= 2.1) NA NANANAno 4.4.0
R6R6 /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library2.6.1 NA R (>= 3.6) NA NA lobstr, testthat (>= 3.0.0) NA MIT + file LICENSE NA NANANAno 4.4.2
RColorBrewerRColorBrewer /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.1-3 NA R (>= 2.0.0) NA NA NA NA Apache License 2.0 NA NANANAno 4.4.0
RcppRcpp /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.0.13-1 NA NA methods, utils NA tinytest, inline, rbenchmark, pkgKitten (>= 0.1.2) NA GPL (>= 2) NA NANANAyes4.4.1
RcppArmadilloRcppArmadillo/Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library14.2.0-1 NA R (>= 3.3.0) Rcpp (>= 1.0.12), stats, utils, methods Rcpptinytest, Matrix (>= 1.3.0), pkgKitten, reticulate, slam NA GPL (>= 2) NA NANANAyes4.4.1
RcppEigenRcppEigen /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.3.4.0.2 NA R (>= 3.6.0) Rcpp (>= 0.11.0), stats, utils RcppMatrix, inline, tinytest, pkgKitten, microbenchmark NA GPL (>= 2) | file LICENSE NA NANANAyes4.4.1
RcppTOMLRcppTOML /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.2.2 NA R (>= 3.3.0) Rcpp (>= 0.11.5) Rcpptinytest NA GPL (>= 2) NA NANANAyes4.4.0
Rttf2pt1Rttf2pt1 /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.3.12 NA R (>= 2.15) NA NA NA NA file LICENSE yesNANANAyes4.4.0
SnowballCSnowballC /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.7.1 NA NA NA NA NA NA BSD_3_clause + file LICENSENA NANANAyes4.4.0
SparseMSparseM /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.84-2 NA R (>= 2.15), methods graphics, stats, utils NA knitr NA GPL (>= 2) NA NANANAyes4.4.0
SuppDistsSuppDists /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.1-9.8 NA R (>= 3.3.0) NA NA RcppZiggurat NA GPL (>= 2) NA NANANAyes4.4.1
XMLXML /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library3.99-0.18 NA R (>= 4.0.0), methods, utils NA NA bitops, RCurl NA BSD_3_clause + file LICENSENA NANANAyes4.4.1
abindabind /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.4-8 NA R (>= 1.5.0) methods, utils NA NA NA MIT + file LICENSE NA NANANAno 4.4.1
...................................................
tinytextinytex /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.54 NA NA xfun (>= 0.48) NA testit, rstudioapi NAMIT + file LICENSE NANANANAno 4.4.1
tmtm /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.7-15 NA R (>= 3.4.0), NLP (>= 0.2-0)Rcpp, parallel, slam (>= 0.1-37), stats, tools, utils, graphics, xml2 BH, Rcpp antiword, filehash, methods, pdftools, Rcampdf, Rgraphviz, Rpoppler, SnowballC, testthat, tm.lexicon.GeneralInquirer NAGPL-3 NANANANAyes4.4.1
tmaptmap /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library3.3-4 NA R (>= 3.5.0), methods tmaptools (>= 3.1), sf (>= 0.9-7), stars (>= 0.5-0), units (>= 0.6-1), grid, RColorBrewer, viridisLite, classInt (>= 0.4-3), htmltools, htmlwidgets, widgetframe, leaflet (>= 2.0.2), leafsync, leafem (>= 0.1), stats, abind, rlang, utils NA rmapshaper, rmarkdown, knitr, png, cartogram, osmdata, ggplot2, dplyr, tidyr, shiny, testthat, covr, av, gifski, s2 NAGPL-3 NANANANAno 4.4.0
tmaptoolstmaptools /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library3.2 NA R (>= 3.5), methods sf (>= 0.9.2), lwgeom (>= 0.1-4), stars (>= 0.4-1), units (>= 0.6-1), grid, magrittr, RColorBrewer, viridisLite, stats, dichromat, XML NA tmap, cols4all, rmapshaper, osmdata, OpenStreetMap, raster, png, shiny, shinyjs NAGPL-3 NANANANAno 4.4.1
toolstools /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library4.4.2 baseNA NA NA codetools, methods, xml2, curl, commonmark, knitr, xfun, mathjaxr, V8 NAPart of R 4.4.2 NANANANAyes4.4.2
topicmodelstopicmodels /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.2-17 NA R (>= 3.5.0) stats4, methods, modeltools, slam, tm (>= 0.6) NA lattice, lda, OAIHarvester, SnowballC NAGPL-2 NANANANAyes4.4.0
tzdbtzdb /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.4.0 NA R (>= 3.5.0) NA cpp11 (>= 0.4.2) covr, testthat (>= 3.0.0) NAMIT + file LICENSE NANANANAyes4.4.0
unitsunits /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.8-5 NA R (>= 3.0.2) Rcpp Rcpp (>= 0.12.10) NISTunits, measurements, xml2, magrittr, pillar (>= 1.3.0), dplyr (>= 1.0.0), vctrs (>= 0.3.1), ggplot2 (> 3.2.1), testthat (>= 3.0.0), vdiffr, knitr, rmarkdown NAGPL-2 NANANANAyes4.4.0
urlcheckerurlchecker /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.0.1 NA R (>= 3.3) cli, curl, tools, xml2 NA covr NAGPL-3 NANANANAno 4.4.0
usethisusethis /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library3.1.0 NA R (>= 3.6) cli (>= 3.0.1), clipr (>= 0.3.0), crayon, curl (>= 2.7), desc (>= 1.4.2), fs (>= 1.3.0), gert (>= 1.4.1), gh (>= 1.2.1), glue (>= 1.3.0), jsonlite, lifecycle (>= 1.0.0), purrr, rappdirs, rlang (>= 1.1.0), rprojroot (>= 1.2), rstudioapi, stats, tools, utils, whisker, withr (>= 2.3.0), yamlNA covr, knitr, magick, pkgload (>= 1.3.2.1), rmarkdown, roxygen2 (>= 7.1.2), spelling (>= 1.2), styler (>= 1.2.0), testthat (>= 3.1.8) NAMIT + file LICENSE NANANANAno 4.4.1
utf8utf8 /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.2.4 NA R (>= 2.10) NA NA cli, covr, knitr, rlang, rmarkdown, testthat (>= 3.0.0), withr NAApache License (== 2.0) | file LICENSENANANANAyes4.4.0
utilsutils /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library4.4.2 baseNA NA NA methods, xml2, commonmark, knitr, jsonlite NAPart of R 4.4.2 NANANANAyes4.4.2
uuiduuid /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.2-1 NA R (>= 2.9.0) NA NA NA NAMIT + file LICENSE NANANANAyes4.4.0
vctrsvctrs /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.6.5 NA R (>= 3.5.0) cli (>= 3.4.0), glue, lifecycle (>= 1.0.3), rlang (>= 1.1.0) NA bit64, covr, crayon, dplyr (>= 0.8.5), generics, knitr, pillar (>= 1.4.4), pkgdown (>= 2.0.1), rmarkdown, testthat (>= 3.0.0), tibble (>= 3.1.3), waldo (>= 0.2.0), withr, xml2, zeallot NAMIT + file LICENSE NANANANAyes4.4.0
viridisLiteviridisLite /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.4.2 NA R (>= 2.10) NA NA hexbin (>= 1.27.0), ggplot2 (>= 1.0.1), testthat, covr NAMIT + file LICENSE NANANANAno 4.4.0
vroomvroom /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.6.5 NA R (>= 3.6) bit64, cli (>= 3.2.0), crayon, glue, hms, lifecycle (>= 1.0.3), methods, rlang (>= 0.4.2), stats, tibble (>= 2.0.0), tidyselect, tzdb (>= 0.1.1), vctrs (>= 0.2.0), withr cpp11 (>= 0.2.0), progress (>= 1.2.1), tzdb (>= 0.1.1)archive, bench (>= 1.1.0), covr, curl, dplyr, forcats, fs, ggplot2, knitr, patchwork, prettyunits, purrr, rmarkdown, rstudioapi, scales, spelling, testthat (>= 2.1.0), tidyr, utils, waldo, xml2NAMIT + file LICENSE NANANANAyes4.4.0
waldowaldo /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.6.1 NA R (>= 4.0) cli, diffobj (>= 0.3.4), glue, methods, rlang (>= 1.1.0) NA bit64, R6, S7, testthat (>= 3.0.0), withr, xml2 NAMIT + file LICENSE NANANANAno 4.4.1
whiskerwhisker /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.4.1 NA NA NA NA markdown NAGPL-3 NANANANAno 4.4.0
widgetframewidgetframe /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.3.1 NA R (>= 3.1.0), htmlwidgets, htmltools, purrr, magrittr, utils, tools NA knitr, rmarkdown NAMIT + file LICENSE NANANANAno 4.4.0
withrwithr /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library3.0.2 NA R (>= 3.6.0) graphics, grDevices NA callr, DBI, knitr, methods, rlang, rmarkdown (>= 2.12), RSQLite, testthat (>= 3.0.0) NAMIT + file LICENSE NANANANAno 4.4.1
wkwk /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.9.4 NA R (>= 2.10) NA NA testthat (>= 3.0.0), vctrs (>= 0.3.0), sf, tibble, readr NAMIT + file LICENSE NANANANAyes4.4.1
xfunxfun /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library0.49 NA R (>= 3.2.0) grDevices, stats, tools NA testit, parallel, codetools, methods, rstudioapi, tinytex (>= 0.30), mime, litedown, commonmark, knitr (>= 1.47), remotes, pak, rhub, renv, curl, xml2, jsonlite, magick, yaml, qs, rmarkdown NAMIT + file LICENSE NANANANAyes4.4.1
xgboostxgboost /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.7.8.1NA R (>= 3.3.0) Matrix (>= 1.1-0), methods, data.table (>= 1.9.6), jsonlite (>= 1.0), NA knitr, rmarkdown, ggplot2 (>= 1.0.1), DiagrammeR (>= 0.9.0), Ckmeans.1d.dp (>= 3.3.1), vcd (>= 1.3), testthat, lintr, igraph (>= 1.0.1), float, crayon, titanic NAApache License (== 2.0) | file LICENSENANANANAyes4.4.0
xml2xml2 /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.3.6 NA R (>= 3.6.0) cli, methods, rlang (>= 1.1.0) NA covr, curl, httr, knitr, magrittr, mockery, rmarkdown, testthat (>= 3.0.0) NAMIT + file LICENSE NANANANAyes4.4.0
xmlparsedataxmlparsedata/Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.0.5 NA R (>= 3.0.0) NA NA covr, testthat, xml2 NAMIT + file LICENSE NANANANAno 4.4.0
xopenxopen /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.0.1 NA R (>= 3.1) processx NA ps, testthat (>= 3.0.0) NAMIT + file LICENSE NANANANAno 4.4.0
xtablextable /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.8-4 NA R (>= 2.10.0) stats, utils NA knitr, plm, zoo, survival NAGPL (>= 2) NANANANAno 4.4.0
yamlyaml /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library2.3.10 NA NA NA NA RUnit NABSD_3_clause + file LICENSE NANANANAyes4.4.0
zipzip /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library2.3.1 NA NA NA NA covr, processx, R6, testthat, withr NAMIT + file LICENSE NANANANAyes4.4.0
zoozoo /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library1.8-12 NA R (>= 3.1.0), stats utils, graphics, grDevices, lattice (>= 0.20-27) NA AER, coda, chron, ggplot2 (>= 3.0.0), mondate, scales, stinepack, strucchange, timeDate, timeSeries, tis, tseries, xts NAGPL-2 | GPL-3 NANANANAyes4.4.0
BH :
 Version 1.84.0-0 installed in /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library 
 Version 1.87.0-1 available at https://cran.r-project.org
cancelled by user

The downloaded binary packages are in
	/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/downloaded_packages


Removing package from '/Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library'
(as 'lib' is unspecified)

值得注意的是,update.packages() 會檢查所有已安裝的套件,並提示你更新哪些有新版本的套件。如果你在 RStudio 中,也可以透過選單「Tools」→「Check for Package Updates」來更新套件。

載入與使用套件

安裝套件後,我們還需要將它載入到當前的 R 環境中才能使用其功能。就像我們下載了 App 後,還需要點開它才能開始使用。

載入套件的方法

在 R 中,有兩種主要方式來使用套件中的函數:

  • 載入整個套件:使用 library()require() 函數
  • 直接引用特定函數:使用 :: 運算子

library() 是最常見的載入套件方式,它會將整個套件載入到當前工作環境:

1
install.packages("ggplot2")
The downloaded binary packages are in
	/var/folders/52/lq6m_ckx0g3f3vvjnlz8hh9h0000gn/T//RtmpypbpVp/downloaded_packages
1
2
3
4
5
6
# 載入 ggplot2 套件
library(ggplot2)

# 現在可以直接使用 ggplot2 中的函數
ggplot(data = mtcars, aes(x = mpg, y = disp)) +
geom_point()

png

載入套件後,你可以直接呼叫該套件中的函數,而不需要加上套件名稱前綴。如果你只需要使用某個套件中的一兩個函數,或者想避免不同套件間函數名稱衝突,可以使用 :: 運算子:

1
2
3
# 不載入套件,直接使用特定函數
ggplot2::ggplot(data = mtcars, ggplot2::aes(x = mpg, y = disp)) +
ggplot2::geom_point()

png

這種方式的優點是明確指出函數來自哪個套件,避免混淆,尤其是當多個套件有相同名稱的函數時。例如,stats::filter()dplyr::filter() 是完全不同的函數,使用 :: 可以明確指定要使用哪一個。

library() vs require()

R 提供了兩個可以載入套件的函數:library()require(),它們的主要區別在於處理錯誤的方式:

1
2
3
4
5
6
7
8
9
10
# 如果套件不存在,會產生錯誤並停止執行
library(nonexistent_package) # 會報錯

# 如果套件不存在,會產生警告但繼續執行
if(require(nonexistent_package)) {
# 套件載入成功時執行的程式碼
} else {
# 套件載入失敗時執行的程式碼
print("套件不存在,請先安裝")
}

一般來說,library() 用於一般的套件載入,而 require() 則多用於條件式載入或錯誤處理情境。

查看套件文件

使用套件前,了解它包含的函數和用法是很重要的,或是可以先上網查詢套件的相關教學,否則在不打開說明書的情況下胡亂使用工具,可能會出現意想不到的嚴重後果(筆者慘痛經驗)。

1
2
3
4
5
6
7
8
9
# 查看套件的說明文件
help(package = "ggplot2")

# 查看套件中特定函數的說明
?ggplot
help("ggplot")

# 查看套件中包含的函數和資料集
ls("package:ggplot2")
  1. '%+%'
  2. '%+replace%'
  3. 'AxisSecondary'
  4. 'Coord'
  5. 'CoordCartesian'
  6. 'CoordFixed'
  7. 'CoordFlip'
  8. 'CoordMap'
  9. 'CoordPolar'
  10. 'CoordQuickmap'
  11. 'CoordRadial'
  12. 'CoordSf'
  13. 'CoordTrans'
  14. 'Facet'
  15. 'FacetGrid'
  16. 'FacetNull'
  17. 'FacetWrap'
  18. 'Geom'
  19. 'GeomAbline'
  20. 'GeomAnnotationMap'
  21. 'GeomArea'
  22. 'GeomBar'
  23. 'GeomBlank'
  24. 'GeomBoxplot'
  25. 'GeomCol'
  26. 'GeomContour'
  27. 'GeomContourFilled'
  28. 'GeomCrossbar'
  29. 'GeomCurve'
  30. 'GeomCustomAnn'
  31. 'GeomDensity'
  32. 'GeomDensity2d'
  33. 'GeomDensity2dFilled'
  34. 'GeomDotplot'
  35. 'GeomErrorbar'
  36. 'GeomErrorbarh'
  37. 'GeomFunction'
  38. 'GeomHex'
  39. 'GeomHline'
  40. 'GeomLabel'
  41. 'GeomLine'
  42. 'GeomLinerange'
  43. 'GeomLogticks'
  44. 'GeomMap'
  45. 'GeomPath'
  46. 'GeomPoint'
  47. 'GeomPointrange'
  48. 'GeomPolygon'
  49. 'GeomQuantile'
  50. 'GeomRaster'
  51. 'GeomRasterAnn'
  52. 'GeomRect'
  53. 'GeomRibbon'
  54. 'GeomRug'
  55. 'GeomSegment'
  56. 'GeomSf'
  57. 'GeomSmooth'
  58. 'GeomSpoke'
  59. 'GeomStep'
  60. 'GeomText'
  61. 'GeomTile'
  62. 'GeomViolin'
  63. 'GeomVline'
  64. 'Guide'
  65. 'GuideAxis'
  66. 'GuideAxisLogticks'
  67. 'GuideAxisStack'
  68. 'GuideAxisTheta'
  69. 'GuideBins'
  70. 'GuideColourbar'
  71. 'GuideColoursteps'
  72. 'GuideCustom'
  73. 'GuideLegend'
  74. 'GuideNone'
  75. 'GuideOld'
  76. 'Layout'
  77. 'Position'
  78. 'PositionDodge'
  79. 'PositionDodge2'
  80. 'PositionFill'
  81. 'PositionIdentity'
  82. 'PositionJitter'
  83. 'PositionJitterdodge'
  84. 'PositionNudge'
  85. 'PositionStack'
  86. 'Scale'
  87. 'ScaleBinned'
  88. 'ScaleBinnedPosition'
  89. 'ScaleContinuous'
  90. 'ScaleContinuousDate'
  91. 'ScaleContinuousDatetime'
  92. 'ScaleContinuousIdentity'
  93. 'ScaleContinuousPosition'
  94. 'ScaleDiscrete'
  95. 'ScaleDiscreteIdentity'
  96. 'ScaleDiscretePosition'
  97. 'Stat'
  98. 'StatAlign'
  99. 'StatBin'
  100. 'StatBin2d'
  101. 'StatBindot'
  102. 'StatBinhex'
  103. 'StatBoxplot'
  104. 'StatContour'
  105. 'StatContourFilled'
  106. 'StatCount'
  107. 'StatDensity'
  108. 'StatDensity2d'
  109. 'StatDensity2dFilled'
  110. 'StatEcdf'
  111. 'StatEllipse'
  112. 'StatFunction'
  113. 'StatIdentity'
  114. 'StatQq'
  115. 'StatQqLine'
  116. 'StatQuantile'
  117. 'StatSf'
  118. 'StatSfCoordinates'
  119. 'StatSmooth'
  120. 'StatSum'
  121. 'StatSummary'
  122. 'StatSummary2d'
  123. 'StatSummaryBin'
  124. 'StatSummaryHex'
  125. 'StatUnique'
  126. 'StatYdensity'
  127. 'aes'
  128. 'aes_'
  129. 'aes_all'
  130. 'aes_auto'
  131. 'aes_q'
  132. 'aes_string'
  133. 'after_scale'
  134. 'after_stat'
  135. 'alpha'
  136. 'annotate'
  137. 'annotation_custom'
  138. 'annotation_logticks'
  139. 'annotation_map'
  140. 'annotation_raster'
  141. 'arrow'
  142. 'as_label'
  143. 'as_labeller'
  144. 'autolayer'
  145. 'autoplot'
  146. 'benchplot'
  147. 'binned_scale'
  148. 'borders'
  149. 'calc_element'
  150. 'check_device'
  151. 'combine_vars'
  152. 'continuous_scale'
  153. 'coord_cartesian'
  154. 'coord_equal'
  155. 'coord_fixed'
  156. 'coord_flip'
  157. 'coord_map'
  158. 'coord_munch'
  159. 'coord_polar'
  160. 'coord_quickmap'
  161. 'coord_radial'
  162. 'coord_sf'
  163. 'coord_trans'
  164. 'cut_interval'
  165. 'cut_number'
  166. 'cut_width'
  167. 'datetime_scale'
  168. 'derive'
  169. 'diamonds'
  170. 'discrete_scale'
  171. 'draw_key_abline'
  172. 'draw_key_blank'
  173. 'draw_key_boxplot'
  174. 'draw_key_crossbar'
  175. 'draw_key_dotplot'
  176. 'draw_key_label'
  177. 'draw_key_linerange'
  178. 'draw_key_path'
  179. 'draw_key_point'
  180. 'draw_key_pointrange'
  181. 'draw_key_polygon'
  182. 'draw_key_rect'
  183. 'draw_key_smooth'
  184. 'draw_key_text'
  185. 'draw_key_timeseries'
  186. 'draw_key_vline'
  187. 'draw_key_vpath'
  188. 'dup_axis'
  189. 'economics'
  190. 'economics_long'
  191. 'el_def'
  192. 'element_blank'
  193. 'element_grob'
  194. 'element_line'
  195. 'element_rect'
  196. 'element_render'
  197. 'element_text'
  198. 'enexpr'
  199. 'enexprs'
  200. 'enquo'
  201. ...
  202. 'scale_alpha_ordinal'
  203. 'scale_color_binned'
  204. 'scale_color_brewer'
  205. 'scale_color_continuous'
  206. 'scale_color_date'
  207. 'scale_color_datetime'
  208. 'scale_color_discrete'
  209. 'scale_color_distiller'
  210. 'scale_color_fermenter'
  211. 'scale_color_gradient'
  212. 'scale_color_gradient2'
  213. 'scale_color_gradientn'
  214. 'scale_color_grey'
  215. 'scale_color_hue'
  216. 'scale_color_identity'
  217. 'scale_color_manual'
  218. 'scale_color_ordinal'
  219. 'scale_color_steps'
  220. 'scale_color_steps2'
  221. 'scale_color_stepsn'
  222. 'scale_color_viridis_b'
  223. 'scale_color_viridis_c'
  224. 'scale_color_viridis_d'
  225. 'scale_colour_binned'
  226. 'scale_colour_brewer'
  227. 'scale_colour_continuous'
  228. 'scale_colour_date'
  229. 'scale_colour_datetime'
  230. 'scale_colour_discrete'
  231. 'scale_colour_distiller'
  232. 'scale_colour_fermenter'
  233. 'scale_colour_gradient'
  234. 'scale_colour_gradient2'
  235. 'scale_colour_gradientn'
  236. 'scale_colour_grey'
  237. 'scale_colour_hue'
  238. 'scale_colour_identity'
  239. 'scale_colour_manual'
  240. 'scale_colour_ordinal'
  241. 'scale_colour_steps'
  242. 'scale_colour_steps2'
  243. 'scale_colour_stepsn'
  244. 'scale_colour_viridis_b'
  245. 'scale_colour_viridis_c'
  246. 'scale_colour_viridis_d'
  247. 'scale_continuous_identity'
  248. 'scale_discrete_identity'
  249. 'scale_discrete_manual'
  250. 'scale_fill_binned'
  251. 'scale_fill_brewer'
  252. 'scale_fill_continuous'
  253. 'scale_fill_date'
  254. 'scale_fill_datetime'
  255. 'scale_fill_discrete'
  256. 'scale_fill_distiller'
  257. 'scale_fill_fermenter'
  258. 'scale_fill_gradient'
  259. 'scale_fill_gradient2'
  260. 'scale_fill_gradientn'
  261. 'scale_fill_grey'
  262. 'scale_fill_hue'
  263. 'scale_fill_identity'
  264. 'scale_fill_manual'
  265. 'scale_fill_ordinal'
  266. 'scale_fill_steps'
  267. 'scale_fill_steps2'
  268. 'scale_fill_stepsn'
  269. 'scale_fill_viridis_b'
  270. 'scale_fill_viridis_c'
  271. 'scale_fill_viridis_d'
  272. 'scale_linetype'
  273. 'scale_linetype_binned'
  274. 'scale_linetype_continuous'
  275. 'scale_linetype_discrete'
  276. 'scale_linetype_identity'
  277. 'scale_linetype_manual'
  278. 'scale_linewidth'
  279. 'scale_linewidth_binned'
  280. 'scale_linewidth_continuous'
  281. 'scale_linewidth_date'
  282. 'scale_linewidth_datetime'
  283. 'scale_linewidth_discrete'
  284. 'scale_linewidth_identity'
  285. 'scale_linewidth_manual'
  286. 'scale_linewidth_ordinal'
  287. 'scale_radius'
  288. 'scale_shape'
  289. 'scale_shape_binned'
  290. 'scale_shape_continuous'
  291. 'scale_shape_discrete'
  292. 'scale_shape_identity'
  293. 'scale_shape_manual'
  294. 'scale_shape_ordinal'
  295. 'scale_size'
  296. 'scale_size_area'
  297. 'scale_size_binned'
  298. 'scale_size_binned_area'
  299. 'scale_size_continuous'
  300. 'scale_size_date'
  301. 'scale_size_datetime'
  302. 'scale_size_discrete'
  303. 'scale_size_identity'
  304. 'scale_size_manual'
  305. 'scale_size_ordinal'
  306. 'scale_type'
  307. 'scale_x_binned'
  308. 'scale_x_continuous'
  309. 'scale_x_date'
  310. 'scale_x_datetime'
  311. 'scale_x_discrete'
  312. 'scale_x_log10'
  313. 'scale_x_reverse'
  314. 'scale_x_sqrt'
  315. 'scale_x_time'
  316. 'scale_y_binned'
  317. 'scale_y_continuous'
  318. 'scale_y_date'
  319. 'scale_y_datetime'
  320. 'scale_y_discrete'
  321. 'scale_y_log10'
  322. 'scale_y_reverse'
  323. 'scale_y_sqrt'
  324. 'scale_y_time'
  325. 'seals'
  326. 'sec_axis'
  327. 'set_last_plot'
  328. 'sf_transform_xy'
  329. 'should_stop'
  330. 'stage'
  331. 'standardise_aes_names'
  332. 'stat'
  333. 'stat_align'
  334. 'stat_bin'
  335. 'stat_bin2d'
  336. 'stat_bin_2d'
  337. 'stat_bin_hex'
  338. 'stat_binhex'
  339. 'stat_boxplot'
  340. 'stat_contour'
  341. 'stat_contour_filled'
  342. 'stat_count'
  343. 'stat_density'
  344. 'stat_density2d'
  345. 'stat_density2d_filled'
  346. 'stat_density_2d'
  347. 'stat_density_2d_filled'
  348. 'stat_ecdf'
  349. 'stat_ellipse'
  350. 'stat_function'
  351. 'stat_identity'
  352. 'stat_qq'
  353. 'stat_qq_line'
  354. 'stat_quantile'
  355. 'stat_sf'
  356. 'stat_sf_coordinates'
  357. 'stat_smooth'
  358. 'stat_spoke'
  359. 'stat_sum'
  360. 'stat_summary'
  361. 'stat_summary2d'
  362. 'stat_summary_2d'
  363. 'stat_summary_bin'
  364. 'stat_summary_hex'
  365. 'stat_unique'
  366. 'stat_ydensity'
  367. 'summarise_coord'
  368. 'summarise_layers'
  369. 'summarise_layout'
  370. 'sym'
  371. 'syms'
  372. 'theme'
  373. 'theme_bw'
  374. 'theme_classic'
  375. 'theme_dark'
  376. 'theme_get'
  377. 'theme_gray'
  378. 'theme_grey'
  379. 'theme_light'
  380. 'theme_linedraw'
  381. 'theme_minimal'
  382. 'theme_replace'
  383. 'theme_set'
  384. 'theme_test'
  385. 'theme_update'
  386. 'theme_void'
  387. 'transform_position'
  388. 'translate_shape_string'
  389. 'txhousing'
  390. 'unit'
  391. 'update_geom_defaults'
  392. 'update_labels'
  393. 'update_stat_defaults'
  394. 'vars'
  395. 'waiver'
  396. 'wrap_dims'
  397. 'xlab'
  398. 'xlim'
  399. 'ylab'
  400. 'ylim'
  401. 'zeroGrob'
Documentation for package 'ggplot2'


		Information on package 'ggplot2'

Description:

Package:                   ggplot2
Version:                   3.5.1
Title:                     Create Elegant Data Visualisations Using the
                           Grammar of Graphics
Authors@R:                 c( person("Hadley", "Wickham", ,
                           "hadley@posit.co", role = "aut", comment =
                           c(ORCID = "0000-0003-4757-117X")),
                           person("Winston", "Chang", role = "aut",
                           comment = c(ORCID = "0000-0002-1576-2126")),
                           person("Lionel", "Henry", role = "aut"),
                           person("Thomas Lin", "Pedersen", ,
                           "thomas.pedersen@posit.co", role = c("aut",
                           "cre"), comment = c(ORCID =
                           "0000-0002-5147-4711")), person("Kohske",
                           "Takahashi", role = "aut"), person("Claus",
                           "Wilke", role = "aut", comment = c(ORCID =
                           "0000-0002-7470-9261")), person("Kara",
                           "Woo", role = "aut", comment = c(ORCID =
                           "0000-0002-5125-4188")), person("Hiroaki",
                           "Yutani", role = "aut", comment = c(ORCID =
                           "0000-0002-3385-7233")), person("Dewey",
                           "Dunnington", role = "aut", comment =
                           c(ORCID = "0000-0002-9415-4582")),
                           person("Teun", "van den Brand", role =
                           "aut", comment = c(ORCID =
                           "0000-0002-9335-7468")), person("Posit,
                           PBC", role = c("cph", "fnd")) )
Description:               A system for 'declaratively' creating
                           graphics, based on "The Grammar of
                           Graphics". You provide the data, tell
                           'ggplot2' how to map variables to
                           aesthetics, what graphical primitives to
                           use, and it takes care of the details.
License:                   MIT + file LICENSE
URL:                       https://ggplot2.tidyverse.org,
                           https://github.com/tidyverse/ggplot2
BugReports:                https://github.com/tidyverse/ggplot2/issues
Depends:                   R (>= 3.5)
Imports:                   cli, glue, grDevices, grid, gtable (>=
                           0.1.1), isoband, lifecycle (> 1.0.1), MASS,
                           mgcv, rlang (>= 1.1.0), scales (>= 1.3.0),
                           stats, tibble, vctrs (>= 0.6.0), withr (>=
                           2.5.0)
Suggests:                  covr, dplyr, ggplot2movies, hexbin, Hmisc,
                           knitr, mapproj, maps, multcomp, munsell,
                           nlme, profvis, quantreg, ragg (>= 1.2.6),
                           RColorBrewer, rmarkdown, rpart, sf (>=
                           0.7-3), svglite (>= 2.1.2), testthat (>=
                           3.1.2), vdiffr (>= 1.0.6), xml2
Enhances:                  sp
VignetteBuilder:           knitr
Config/Needs/website:      ggtext, tidyr, forcats,
                           tidyverse/tidytemplate
Config/testthat/edition:   3
Encoding:                  UTF-8
LazyData:                  true
RoxygenNote:               7.3.1
Collate:                   'ggproto.R' 'ggplot-global.R' 'aaa-.R'
                           'aes-colour-fill-alpha.R' 'aes-evaluation.R'
                           'aes-group-order.R'
                           'aes-linetype-size-shape.R' 'aes-position.R'
                           'compat-plyr.R' 'utilities.R' 'aes.R'
                           'utilities-checks.R' 'legend-draw.R'
                           'geom-.R' 'annotation-custom.R'
                           'annotation-logticks.R' 'geom-polygon.R'
                           'geom-map.R' 'annotation-map.R'
                           'geom-raster.R' 'annotation-raster.R'
                           'annotation.R' 'autolayer.R' 'autoplot.R'
                           'axis-secondary.R' 'backports.R' 'bench.R'
                           'bin.R' 'coord-.R' 'coord-cartesian-.R'
                           'coord-fixed.R' 'coord-flip.R' 'coord-map.R'
                           'coord-munch.R' 'coord-polar.R'
                           'coord-quickmap.R' 'coord-radial.R'
                           'coord-sf.R' 'coord-transform.R' 'data.R'
                           'docs_layer.R' 'facet-.R' 'facet-grid-.R'
                           'facet-null.R' 'facet-wrap.R' 'fortify-lm.R'
                           'fortify-map.R' 'fortify-multcomp.R'
                           'fortify-spatial.R' 'fortify.R' 'stat-.R'
                           'geom-abline.R' 'geom-rect.R' 'geom-bar.R'
                           'geom-bin2d.R' 'geom-blank.R'
                           'geom-boxplot.R' 'geom-col.R' 'geom-path.R'
                           'geom-contour.R' 'geom-count.R'
                           'geom-crossbar.R' 'geom-segment.R'
                           'geom-curve.R' 'geom-defaults.R'
                           'geom-ribbon.R' 'geom-density.R'
                           'geom-density2d.R' 'geom-dotplot.R'
                           'geom-errorbar.R' 'geom-errorbarh.R'
                           'geom-freqpoly.R' 'geom-function.R'
                           'geom-hex.R' 'geom-histogram.R'
                           'geom-hline.R' 'geom-jitter.R'
                           'geom-label.R' 'geom-linerange.R'
                           'geom-point.R' 'geom-pointrange.R'
                           'geom-quantile.R' 'geom-rug.R' 'geom-sf.R'
                           'geom-smooth.R' 'geom-spoke.R' 'geom-text.R'
                           'geom-tile.R' 'geom-violin.R' 'geom-vline.R'
                           'ggplot2-package.R' 'grob-absolute.R'
                           'grob-dotstack.R' 'grob-null.R' 'grouping.R'
                           'theme-elements.R' 'guide-.R' 'guide-axis.R'
                           'guide-axis-logticks.R' 'guide-axis-stack.R'
                           'guide-axis-theta.R' 'guide-legend.R'
                           'guide-bins.R' 'guide-colorbar.R'
                           'guide-colorsteps.R' 'guide-custom.R'
                           'layer.R' 'guide-none.R' 'guide-old.R'
                           'guides-.R' 'guides-grid.R' 'hexbin.R'
                           'import-standalone-obj-type.R'
                           'import-standalone-types-check.R'
                           'labeller.R' 'labels.R' 'layer-sf.R'
                           'layout.R' 'limits.R' 'margins.R'
                           'performance.R' 'plot-build.R'
                           'plot-construction.R' 'plot-last.R' 'plot.R'
                           'position-.R' 'position-collide.R'
                           'position-dodge.R' 'position-dodge2.R'
                           'position-identity.R' 'position-jitter.R'
                           'position-jitterdodge.R' 'position-nudge.R'
                           'position-stack.R' 'quick-plot.R'
                           'reshape-add-margins.R' 'save.R' 'scale-.R'
                           'scale-alpha.R' 'scale-binned.R'
                           'scale-brewer.R' 'scale-colour.R'
                           'scale-continuous.R' 'scale-date.R'
                           'scale-discrete-.R' 'scale-expansion.R'
                           'scale-gradient.R' 'scale-grey.R'
                           'scale-hue.R' 'scale-identity.R'
                           'scale-linetype.R' 'scale-linewidth.R'
                           'scale-manual.R' 'scale-shape.R'
                           'scale-size.R' 'scale-steps.R'
                           'scale-type.R' 'scale-view.R'
                           'scale-viridis.R' 'scales-.R' 'stat-align.R'
                           'stat-bin.R' 'stat-bin2d.R' 'stat-bindot.R'
                           'stat-binhex.R' 'stat-boxplot.R'
                           'stat-contour.R' 'stat-count.R'
                           'stat-density-2d.R' 'stat-density.R'
                           'stat-ecdf.R' 'stat-ellipse.R'
                           'stat-function.R' 'stat-identity.R'
                           'stat-qq-line.R' 'stat-qq.R'
                           'stat-quantilemethods.R'
                           'stat-sf-coordinates.R' 'stat-sf.R'
                           'stat-smooth-methods.R' 'stat-smooth.R'
                           'stat-sum.R' 'stat-summary-2d.R'
                           'stat-summary-bin.R' 'stat-summary-hex.R'
                           'stat-summary.R' 'stat-unique.R'
                           'stat-ydensity.R' 'summarise-plot.R'
                           'summary.R' 'theme.R' 'theme-defaults.R'
                           'theme-current.R' 'utilities-break.R'
                           'utilities-grid.R' 'utilities-help.R'
                           'utilities-matrix.R' 'utilities-patterns.R'
                           'utilities-resolution.R'
                           'utilities-tidy-eval.R' 'zxx.R' 'zzz.R'
NeedsCompilation:          no
Packaged:                  2024-04-22 10:39:16 UTC; thomas
Author:                    Hadley Wickham [aut]
                           (<https://orcid.org/0000-0003-4757-117X>),
                           Winston Chang [aut]
                           (<https://orcid.org/0000-0002-1576-2126>),
                           Lionel Henry [aut], Thomas Lin Pedersen
                           [aut, cre]
                           (<https://orcid.org/0000-0002-5147-4711>),
                           Kohske Takahashi [aut], Claus Wilke [aut]
                           (<https://orcid.org/0000-0002-7470-9261>),
                           Kara Woo [aut]
                           (<https://orcid.org/0000-0002-5125-4188>),
                           Hiroaki Yutani [aut]
                           (<https://orcid.org/0000-0002-3385-7233>),
                           Dewey Dunnington [aut]
                           (<https://orcid.org/0000-0002-9415-4582>),
                           Teun van den Brand [aut]
                           (<https://orcid.org/0000-0002-9335-7468>),
                           Posit, PBC [cph, fnd]
Maintainer:                Thomas Lin Pedersen
                           <thomas.pedersen@posit.co>
Repository:                CRAN
Date/Publication:          2024-04-23 08:00:08 UTC
Built:                     R 4.4.0; ; 2024-04-23 11:40:42 UTC; unix

Index:

+.gg                    Add components to a plot
CoordSf                 Visualise sf objects
aes                     Construct aesthetic mappings
aes_colour_fill_alpha   Colour related aesthetics: colour, fill, and
                        alpha
aes_eval                Control aesthetic evaluation
aes_group_order         Aesthetics: grouping
aes_linetype_size_shape
                        Differentiation related aesthetics: linetype,
                        size, shape
aes_position            Position related aesthetics: x, y, xmin, xmax,
                        ymin, ymax, xend, yend
annotate                Create an annotation layer
annotation_custom       Annotation: Custom grob
annotation_logticks     Annotation: log tick marks
annotation_map          Annotation: a map
annotation_raster       Annotation: high-performance rectangular tiling
autolayer               Create a ggplot layer appropriate to a
                        particular data type
automatic_plotting      Tailoring plots to particular data types
autoplot                Create a complete ggplot appropriate to a
                        particular data type
borders                 Create a layer of map borders
coord_cartesian         Cartesian coordinates
coord_fixed             Cartesian coordinates with fixed "aspect ratio"
coord_flip              Cartesian coordinates with x and y flipped
coord_map               Map projections
coord_polar             Polar coordinates
coord_trans             Transformed Cartesian coordinate system
cut_interval            Discretise numeric data into categorical
diamonds                Prices of over 50,000 round cut diamonds
draw_key                Key glyphs for legends
economics               US economic time series
element_blank           Theme elements
expand_limits           Expand the plot limits, using data
expansion               Generate expansion vector for scales
facet_grid              Lay out panels in a grid
facet_wrap              Wrap a 1d ribbon of panels into 2d
faithfuld               2d density estimate of Old Faithful data
fortify                 Fortify a model with data.
geom_abline             Reference lines: horizontal, vertical, and
                        diagonal
geom_bar                Bar charts
geom_bin_2d             Heatmap of 2d bin counts
geom_blank              Draw nothing
geom_boxplot            A box and whiskers plot (in the style of Tukey)
geom_contour            2D contours of a 3D surface
geom_count              Count overlapping points
geom_crossbar           Vertical intervals: lines, crossbars &
                        errorbars
geom_density            Smoothed density estimates
geom_density_2d         Contours of a 2D density estimate
geom_dotplot            Dot plot
geom_errorbarh          Horizontal error bars
geom_freqpoly           Histograms and frequency polygons
geom_function           Draw a function as a continuous curve
geom_hex                Hexagonal heatmap of 2d bin counts
geom_jitter             Jittered points
geom_label              Text
geom_map                Polygons from a reference map
geom_path               Connect observations
geom_point              Points
geom_polygon            Polygons
geom_qq_line            A quantile-quantile plot
geom_quantile           Quantile regression
geom_raster             Rectangles
geom_ribbon             Ribbons and area plots
geom_rug                Rug plots in the margins
geom_segment            Line segments and curves
geom_smooth             Smoothed conditional means
geom_spoke              Line segments parameterised by location,
                        direction and distance
geom_violin             Violin plot
get_alt_text            Extract alt text from a plot
ggplot                  Create a new ggplot
ggproto                 Create a new ggproto object
ggsave                  Save a ggplot (or other grid object) with
                        sensible defaults
guide_axis              Axis guide
guide_axis_logticks     Axis with logarithmic tick marks
guide_axis_stack        Stacked axis guides
guide_axis_theta        Angle axis guide
guide_bins              A binned version of guide_legend
guide_colourbar         Continuous colour bar guide
guide_coloursteps       Discretized colourbar guide
guide_custom            Custom guides
guide_legend            Legend guide
guide_none              Empty guide
guides                  Set guides for each scale
hmisc                   A selection of summary functions from Hmisc
label_bquote            Label with mathematical expressions
labeller                Construct labelling specification
labellers               Useful labeller functions
labs                    Modify axis, legend, and plot labels
layer_geoms             Layer geometry display
layer_positions         Layer position adjustments
layer_stats             Layer statistical transformations
lims                    Set scale limits
luv_colours             'colors()' in Luv space
mean_se                 Calculate mean and standard error of the mean
midwest                 Midwest demographics
mpg                     Fuel economy data from 1999 to 2008 for 38
                        popular models of cars
msleep                  An updated and expanded version of the mammals
                        sleep dataset
position_dodge          Dodge overlapping objects side-to-side
position_identity       Don't adjust position
position_jitter         Jitter points to avoid overplotting
position_jitterdodge    Simultaneously dodge and jitter
position_nudge          Nudge points a fixed distance
position_stack          Stack overlapping objects on top of each
                        another
presidential            Terms of 12 presidents from Eisenhower to Trump
print.ggplot            Explicitly draw plot
print.ggproto           Format or print a ggproto object
qplot                   Quick plot
resolution              Compute the "resolution" of a numeric vector
scale_alpha             Alpha transparency scales
scale_colour_brewer     Sequential, diverging and qualitative colour
                        scales from ColorBrewer
scale_colour_continuous
                        Continuous and binned colour scales
scale_colour_discrete   Discrete colour scales
scale_colour_gradient   Gradient colour scales
scale_colour_grey       Sequential grey colour scales
scale_colour_hue        Evenly spaced colours for discrete data
scale_colour_identity   Use values without scaling
scale_colour_manual     Create your own discrete scale
scale_colour_steps      Binned gradient colour scales
scale_colour_viridis_d
                        Viridis colour scales from viridisLite
scale_linetype          Scale for line patterns
scale_linewidth         Scales for line width
scale_shape             Scales for shapes, aka glyphs
scale_size              Scales for area or radius
scale_x_binned          Positional scales for binning continuous data
                        (x & y)
scale_x_continuous      Position scales for continuous data (x & y)
scale_x_date            Position scales for date/time data
scale_x_discrete        Position scales for discrete data
seals                   Vector field of seal movements
sec_axis                Specify a secondary axis
stat_ecdf               Compute empirical cumulative distribution
stat_ellipse            Compute normal data ellipses
stat_identity           Leave data as is
stat_sf_coordinates     Extract coordinates from 'sf' objects
stat_summary_2d         Bin and summarise in 2d (rectangle & hexagons)
stat_summary_bin        Summarise y values at unique/binned x
stat_unique             Remove duplicates
theme                   Modify components of a theme
theme_get               Get, set, and modify the active theme
theme_grey              Complete themes
txhousing               Housing sales in TX
vars                    Quote faceting variables

Further information is available in the following vignettes in
directory
'/Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library/ggplot2/doc':

extending-ggplot2: Extending ggplot2 (source, pdf)
ggplot2-in-packages: Using ggplot2 in packages (source, pdf)
ggplot2-specs: Aesthetic specifications (source, pdf)
ggplot2: Introduction to ggplot2 (source, pdf)

ggplot                 package:ggplot2                 R Documentation

_C_r_e_a_t_e _a _n_e_w _g_g_p_l_o_t

_D_e_s_c_r_i_p_t_i_o_n:

     'ggplot()' initializes a ggplot object. It can be used to declare
     the input data frame for a graphic and to specify the set of plot
     aesthetics intended to be common throughout all subsequent layers
     unless specifically overridden.

_U_s_a_g_e:

     ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())
     
_A_r_g_u_m_e_n_t_s:

    data: Default dataset to use for plot. If not already a data.frame,
          will be converted to one by 'fortify()'. If not specified,
          must be supplied in each layer added to the plot.

 mapping: Default list of aesthetic mappings to use for plot. If not
          specified, must be supplied in each layer added to the plot.

     ...: Other arguments passed on to methods. Not currently used.

environment: *[Deprecated]* Used prior to tidy evaluation.

_D_e_t_a_i_l_s:

     'ggplot()' is used to construct the initial plot object, and is
     almost always followed by a plus sign ('+') to add components to
     the plot.

     There are three common patterns used to invoke 'ggplot()':

        * ggplot(data = df, mapping = aes(x, y, other aesthetics))

        * 'ggplot(data = df)'

        * 'ggplot()'

     The first pattern is recommended if all layers use the same data
     and the same set of aesthetics, although this method can also be
     used when adding a layer using data from another data frame.

     The second pattern specifies the default data frame to use for the
     plot, but no aesthetics are defined up front. This is useful when
     one data frame is used predominantly for the plot, but the
     aesthetics vary from one layer to another.

     The third pattern initializes a skeleton 'ggplot' object, which is
     fleshed out as layers are added. This is useful when multiple data
     frames are used to produce different layers, as is often the case
     in complex graphics.

     The data = and mapping = specifications in the arguments are
     optional (and are often omitted in practice), so long as the data
     and the mapping values are passed into the function in the right
     order. In the examples below, however, they are left in place for
     clarity.

_S_e_e _A_l_s_o:

     The first steps chapter of the online ggplot2 book.

_E_x_a_m_p_l_e_s:

     # Create a data frame with some sample data, then create a data frame
     # containing the mean value for each group in the sample data.
     set.seed(1)
     
     sample_df <- data.frame(
       group = factor(rep(letters[1:3], each = 10)),
       value = rnorm(30)
     )
     
     group_means_df <- setNames(
       aggregate(value ~ group, sample_df, mean),
       c("group", "group_mean")
     )
     
     # The following three code blocks create the same graphic, each using one
     # of the three patterns specified above. In each graphic, the sample data
     # are plotted in the first layer and the group means data frame is used to
     # plot larger red points on top of the sample data in the second layer.
     
     # Pattern 1
     # Both the `data` and `mapping` arguments are passed into the `ggplot()`
     # call. Those arguments are omitted in the first `geom_point()` layer
     # because they get passed along from the `ggplot()` call. Note that the
     # second `geom_point()` layer re-uses the `x = group` aesthetic through
     # that mechanism but overrides the y-position aesthetic.
     ggplot(data = sample_df, mapping = aes(x = group, y = value)) +
       geom_point() +
       geom_point(
         mapping = aes(y = group_mean), data = group_means_df,
         colour = 'red', size = 3
       )
     
     # Pattern 2
     # Same plot as above, passing only the `data` argument into the `ggplot()`
     # call. The `mapping` arguments are now required in each `geom_point()`
     # layer because there is no `mapping` argument passed along from the
     # `ggplot()` call.
     ggplot(data = sample_df) +
       geom_point(mapping = aes(x = group, y = value)) +
       geom_point(
         mapping = aes(x = group, y = group_mean), data = group_means_df,
         colour = 'red', size = 3
       )
     
     # Pattern 3
     # Same plot as above, passing neither the `data` or `mapping` arguments
     # into the `ggplot()` call. Both those arguments are now required in
     # each `geom_point()` layer. This pattern can be particularly useful when
     # creating more complex graphics with many layers using data from multiple
     # data frames.
     ggplot() +
       geom_point(mapping = aes(x = group, y = value), data = sample_df) +
       geom_point(
         mapping = aes(x = group, y = group_mean), data = group_means_df,
         colour = 'red', size = 3
       )
     

ggplot                 package:ggplot2                 R Documentation

_C_r_e_a_t_e _a _n_e_w _g_g_p_l_o_t

_D_e_s_c_r_i_p_t_i_o_n:

     'ggplot()' initializes a ggplot object. It can be used to declare
     the input data frame for a graphic and to specify the set of plot
     aesthetics intended to be common throughout all subsequent layers
     unless specifically overridden.

_U_s_a_g_e:

     ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())
     
_A_r_g_u_m_e_n_t_s:

    data: Default dataset to use for plot. If not already a data.frame,
          will be converted to one by 'fortify()'. If not specified,
          must be supplied in each layer added to the plot.

 mapping: Default list of aesthetic mappings to use for plot. If not
          specified, must be supplied in each layer added to the plot.

     ...: Other arguments passed on to methods. Not currently used.

environment: *[Deprecated]* Used prior to tidy evaluation.

_D_e_t_a_i_l_s:

     'ggplot()' is used to construct the initial plot object, and is
     almost always followed by a plus sign ('+') to add components to
     the plot.

     There are three common patterns used to invoke 'ggplot()':

        * ggplot(data = df, mapping = aes(x, y, other aesthetics))

        * 'ggplot(data = df)'

        * 'ggplot()'

     The first pattern is recommended if all layers use the same data
     and the same set of aesthetics, although this method can also be
     used when adding a layer using data from another data frame.

     The second pattern specifies the default data frame to use for the
     plot, but no aesthetics are defined up front. This is useful when
     one data frame is used predominantly for the plot, but the
     aesthetics vary from one layer to another.

     The third pattern initializes a skeleton 'ggplot' object, which is
     fleshed out as layers are added. This is useful when multiple data
     frames are used to produce different layers, as is often the case
     in complex graphics.

     The data = and mapping = specifications in the arguments are
     optional (and are often omitted in practice), so long as the data
     and the mapping values are passed into the function in the right
     order. In the examples below, however, they are left in place for
     clarity.

_S_e_e _A_l_s_o:

     The first steps chapter of the online ggplot2 book.

_E_x_a_m_p_l_e_s:

     # Create a data frame with some sample data, then create a data frame
     # containing the mean value for each group in the sample data.
     set.seed(1)
     
     sample_df <- data.frame(
       group = factor(rep(letters[1:3], each = 10)),
       value = rnorm(30)
     )
     
     group_means_df <- setNames(
       aggregate(value ~ group, sample_df, mean),
       c("group", "group_mean")
     )
     
     # The following three code blocks create the same graphic, each using one
     # of the three patterns specified above. In each graphic, the sample data
     # are plotted in the first layer and the group means data frame is used to
     # plot larger red points on top of the sample data in the second layer.
     
     # Pattern 1
     # Both the `data` and `mapping` arguments are passed into the `ggplot()`
     # call. Those arguments are omitted in the first `geom_point()` layer
     # because they get passed along from the `ggplot()` call. Note that the
     # second `geom_point()` layer re-uses the `x = group` aesthetic through
     # that mechanism but overrides the y-position aesthetic.
     ggplot(data = sample_df, mapping = aes(x = group, y = value)) +
       geom_point() +
       geom_point(
         mapping = aes(y = group_mean), data = group_means_df,
         colour = 'red', size = 3
       )
     
     # Pattern 2
     # Same plot as above, passing only the `data` argument into the `ggplot()`
     # call. The `mapping` arguments are now required in each `geom_point()`
     # layer because there is no `mapping` argument passed along from the
     # `ggplot()` call.
     ggplot(data = sample_df) +
       geom_point(mapping = aes(x = group, y = value)) +
       geom_point(
         mapping = aes(x = group, y = group_mean), data = group_means_df,
         colour = 'red', size = 3
       )
     
     # Pattern 3
     # Same plot as above, passing neither the `data` or `mapping` arguments
     # into the `ggplot()` call. Both those arguments are now required in
     # each `geom_point()` layer. This pattern can be particularly useful when
     # creating more complex graphics with many layers using data from multiple
     # data frames.
     ggplot() +
       geom_point(mapping = aes(x = group, y = value), data = sample_df) +
       geom_point(
         mapping = aes(x = group, y = group_mean), data = group_means_df,
         colour = 'red', size = 3
       )
     

如果你在 RStudio 中,還可以使用 Help 面板瀏覽套件的文件,或者使用 Tab 鍵自動完成來探索套件中的函數。

套件的命名空間與衝突

在同時載入多個套件時,可能會遇到函數名稱衝突的問題。例如,dplyrstats 套件都有 filter() 函數,但功能完全不同:

1
2
3
4
5
6
7
8
9
10
# 載入兩個都有 filter 函數的套件
library(stats) # R 基礎套件,自動載入
library(dplyr)

# 此時直接呼叫 filter() 會使用最後載入的套件中的函數(這裡是 dplyr)
filter(mtcars, mpg > 20)

# 使用 :: 運算子可以明確指定要使用哪個套件的函數
stats::filter(1:10, rep(1, 3)) # 使用 stats 套件的 filter(時間序列濾波)
dplyr::filter(mtcars, mpg > 20) # 使用 dplyr 套件的 filter(資料篩選)
Attaching package: 'dplyr'


The following objects are masked from 'package:stats':

    filter, lag


The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
A data.frame: 14 x 11
mpgcyldisphpdratwtqsecvsamgearcarb
<dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl>
Mazda RX421.06160.01103.902.62016.460144
Mazda RX4 Wag21.06160.01103.902.87517.020144
Datsun 71022.84108.0 933.852.32018.611141
Hornet 4 Drive21.46258.01103.083.21519.441031
Merc 240D24.44146.7 623.693.19020.001042
Merc 23022.84140.8 953.923.15022.901042
Fiat 12832.44 78.7 664.082.20019.471141
Honda Civic30.44 75.7 524.931.61518.521142
Toyota Corolla33.94 71.1 654.221.83519.901141
Toyota Corona21.54120.1 973.702.46520.011031
Fiat X1-927.34 79.0 664.081.93518.901141
Porsche 914-226.04120.3 914.432.14016.700152
Lotus Europa30.44 95.11133.771.51316.901152
Volvo 142E21.44121.01094.112.78018.601142

A Time Series:

  1. <NA>
  2. 6
  3. 9
  4. 12
  5. 15
  6. 18
  7. 21
  8. 24
  9. 27
  10. <NA>
A data.frame: 14 x 11
mpgcyldisphpdratwtqsecvsamgearcarb
<dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl><dbl>
Mazda RX421.06160.01103.902.62016.460144
Mazda RX4 Wag21.06160.01103.902.87517.020144
Datsun 71022.84108.0 933.852.32018.611141
Hornet 4 Drive21.46258.01103.083.21519.441031
Merc 240D24.44146.7 623.693.19020.001042
Merc 23022.84140.8 953.923.15022.901042
Fiat 12832.44 78.7 664.082.20019.471141
Honda Civic30.44 75.7 524.931.61518.521142
Toyota Corolla33.94 71.1 654.221.83519.901141
Toyota Corona21.54120.1 973.702.46520.011031
Fiat X1-927.34 79.0 664.081.93518.901141
Porsche 914-226.04120.3 914.432.14016.700152
Lotus Europa30.44 95.11133.771.51316.901152
Volvo 142E21.44121.01094.112.78018.601142

當遇到函數名稱衝突時,R 會顯示警告訊息,告訴你某些函數被遮蔽(masked)了。此時,最後載入的套件中的函數會覆蓋先前載入的同名函數。因此,為了避免混淆,建議在程式碼中使用 :: 運算子明確指定函數來源,或是注意套件載入的順序。

理解套件依賴關係

在 R 的生態系統中,套件並非獨立存在的,而是存在著錯綜複雜的相互依賴關係。了解這些依賴關係,有助於我們在遇到問題時更容易排除故障,也能幫助我們設計更可靠的 R 程式。例如在載入 A 套件時,他的依賴套件 B、C、D 在安裝上有問題,可能會造成 A 套件的使用上出現錯誤。

套件依賴關係的類型

R 套件的依賴關係主要有以下幾種:

  1. Imports:套件執行時必須存在的其他套件。當你安裝一個套件時,其 Imports 中的套件也會自動安裝。
  2. Depends:與 Imports 類似,但 Depends 中的套件會自動載入(相當於呼叫 library())。
  3. Suggests:非必須但推薦安裝的套件,通常用於提供額外功能或範例。
  4. Enhances:套件可以增強的其他套件,但不是必須的。

查看套件的依賴關係

我們可以使用 packageDescription() 函數查看套件的詳細資訊,包括其依賴關係:

1
2
3
4
5
6
7
# 查看 ggplot2 套件的描述信息
packageDescription("ggplot2")

# 只查看依賴關係
packageDescription("ggplot2")$Imports
packageDescription("ggplot2")$Depends
packageDescription("ggplot2")$Suggests
Package: ggplot2
Version: 3.5.1
Title: Create Elegant Data Visualisations Using the Grammar of Graphics
Authors@R: c( person("Hadley", "Wickham", , "hadley@posit.co", role =
        "aut", comment = c(ORCID = "0000-0003-4757-117X")),
        person("Winston", "Chang", role = "aut", comment = c(ORCID =
        "0000-0002-1576-2126")), person("Lionel", "Henry", role =
        "aut"), person("Thomas Lin", "Pedersen", ,
        "thomas.pedersen@posit.co", role = c("aut", "cre"), comment =
        c(ORCID = "0000-0002-5147-4711")), person("Kohske",
        "Takahashi", role = "aut"), person("Claus", "Wilke", role =
        "aut", comment = c(ORCID = "0000-0002-7470-9261")),
        person("Kara", "Woo", role = "aut", comment = c(ORCID =
        "0000-0002-5125-4188")), person("Hiroaki", "Yutani", role =
        "aut", comment = c(ORCID = "0000-0002-3385-7233")),
        person("Dewey", "Dunnington", role = "aut", comment = c(ORCID =
        "0000-0002-9415-4582")), person("Teun", "van den Brand", role =
        "aut", comment = c(ORCID = "0000-0002-9335-7468")),
        person("Posit, PBC", role = c("cph", "fnd")) )
Description: A system for 'declaratively' creating graphics, based on
        "The Grammar of Graphics". You provide the data, tell 'ggplot2'
        how to map variables to aesthetics, what graphical primitives
        to use, and it takes care of the details.
License: MIT + file LICENSE
URL: https://ggplot2.tidyverse.org,
        https://github.com/tidyverse/ggplot2
BugReports: https://github.com/tidyverse/ggplot2/issues
Depends: R (>= 3.5)
Imports: cli, glue, grDevices, grid, gtable (>= 0.1.1), isoband,
        lifecycle (> 1.0.1), MASS, mgcv, rlang (>= 1.1.0), scales (>=
        1.3.0), stats, tibble, vctrs (>= 0.6.0), withr (>= 2.5.0)
Suggests: covr, dplyr, ggplot2movies, hexbin, Hmisc, knitr, mapproj,
        maps, multcomp, munsell, nlme, profvis, quantreg, ragg (>=
        1.2.6), RColorBrewer, rmarkdown, rpart, sf (>= 0.7-3), svglite
        (>= 2.1.2), testthat (>= 3.1.2), vdiffr (>= 1.0.6), xml2
Enhances: sp
VignetteBuilder: knitr
Config/Needs/website: ggtext, tidyr, forcats, tidyverse/tidytemplate
Config/testthat/edition: 3
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.3.1
Collate: 'ggproto.R' 'ggplot-global.R' 'aaa-.R'
        'aes-colour-fill-alpha.R' .....
NeedsCompilation: no
Packaged: 2024-04-22 10:39:16 UTC; thomas
Author: Hadley Wickham [aut] (<https://orcid.org/0000-0003-4757-117X>),
        Winston Chang [aut] (<https://orcid.org/0000-0002-1576-2126>),
        Lionel Henry [aut], Thomas Lin Pedersen [aut, cre]
        (<https://orcid.org/0000-0002-5147-4711>), Kohske Takahashi
        [aut], Claus Wilke [aut]
        (<https://orcid.org/0000-0002-7470-9261>), Kara Woo [aut]
        (<https://orcid.org/0000-0002-5125-4188>), Hiroaki Yutani [aut]
        (<https://orcid.org/0000-0002-3385-7233>), Dewey Dunnington
        [aut] (<https://orcid.org/0000-0002-9415-4582>), Teun van den
        Brand [aut] (<https://orcid.org/0000-0002-9335-7468>), Posit,
        PBC [cph, fnd]
Maintainer: Thomas Lin Pedersen <thomas.pedersen@posit.co>
Repository: CRAN
Date/Publication: 2024-04-23 08:00:08 UTC
Built: R 4.4.0; ; 2024-04-23 11:40:42 UTC; unix

-- File: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library/ggplot2/Meta/package.rds 

‘cli, glue, grDevices, grid, gtable (>= 0.1.1), isoband,\nlifecycle (> 1.0.1), MASS, mgcv, rlang (>= 1.1.0), scales (>=\n1.3.0), stats, tibble, vctrs (>= 0.6.0), withr (>= 2.5.0)’

‘R (>= 3.5)’

‘covr, dplyr, ggplot2movies, hexbin, Hmisc, knitr, mapproj,\nmaps, multcomp, munsell, nlme, profvis, quantreg, ragg (>=\n1.2.6), RColorBrewer, rmarkdown, rpart, sf (>= 0.7-3), svglite\n(>= 2.1.2), testthat (>= 3.1.2), vdiffr (>= 1.0.6), xml2’

此外,tools::package_dependencies() 函數可以更系統地檢視套件的依賴:

1
2
3
4
5
# 查看直接依賴
tools::package_dependencies("ggplot2", which = c("Imports", "Depends"))

# 查看所有依賴(包括依賴的依賴)
tools::package_dependencies("ggplot2", which = c("Imports", "Depends"), recursive = TRUE)

$ggplot2 =

  1. 'cli'
  2. 'glue'
  3. 'grDevices'
  4. 'grid'
  5. 'gtable'
  6. 'isoband'
  7. 'lifecycle'
  8. 'MASS'
  9. 'mgcv'
  10. 'rlang'
  11. 'scales'
  12. 'stats'
  13. 'tibble'
  14. 'vctrs'
  15. 'withr'

$ggplot2 =

  1. 'cli'
  2. 'glue'
  3. 'grDevices'
  4. 'grid'
  5. 'gtable'
  6. 'isoband'
  7. 'lifecycle'
  8. 'MASS'
  9. 'mgcv'
  10. 'rlang'
  11. 'scales'
  12. 'stats'
  13. 'tibble'
  14. 'vctrs'
  15. 'withr'
  16. 'methods'
  17. 'graphics'
  18. 'utils'
  19. 'Matrix'
  20. 'splines'
  21. 'nlme'
  22. 'farver'
  23. 'labeling'
  24. 'munsell'
  25. 'R6'
  26. 'RColorBrewer'
  27. 'viridisLite'
  28. 'fansi'
  29. 'magrittr'
  30. 'pillar'
  31. 'pkgconfig'
  32. 'lattice'
  33. 'colorspace'
  34. 'utf8'

小結

在 R 語言中,資料型別決定了變數能進行哪些操作、適用哪些函數、甚至影響統計模型的推論結果。因此,不論是初學者還是進階使用者,都應該養成「隨時檢查變數型別」的好習慣。當你每次從外部匯入資料(如 CSV、Excel、資料庫)或執行前處理時,建議都先用 class()typeof()is.xxx() 這些工具一一檢查每個變數的型別,再進一步決定是否需要轉型(如 as.numeric()、as.factor() 等),這樣可以大幅減少錯誤的機率,也能讓你的資料分析流程更順暢。此外,熟悉運算子的優先順序,但不要過度依賴它,適當使用括號可以讓程式碼更可讀(readable)。