# 10 多樣的資料結構：向量與因素向量

## 10.1 R 語言三大資料結構

• 一維
• 向量（vector）
• 因素向量（factor）
• 二維
• 矩陣（matrix）
• 資料框（data.frame）
• 多維
• 陣列（array）
• 清單（list）

## 10.2 向量

four_seasons <- c("spring", "summer", "autumn", "winter")
four_seasons
## [1] "spring" "summer" "autumn" "winter"

weekends <- c("Saturday", "Sunday")
my_lucky_numbers <- c(7L, 24L)
weekends
## [1] "Saturday" "Sunday"
my_lucky_numbers
## [1]  7 24

four_seasons <- c("spring", "summer", "autumn", "winter")
favorite_season <- four_seasons[3]
favorite_season
## [1] "autumn"

four_seasons <- c("spring", "summer", "autumn", "winter")
favorite_seasons <- four_seasons[c(-2, -4)]
favorite_seasons
## [1] "spring" "autumn"

lucky_numbers <- c(7L, 24)
class(lucky_numbers[1])
## [1] "numeric"

lucky_numbers <- c(7L, FALSE)
lucky_numbers
## [1] 7 0
class(lucky_numbers[2])
## [1] "integer"

mixed_vars <- c(TRUE, 7L, 24, "spring")
mixed_vars
## [1] "TRUE"   "7"      "24"     "spring"
class(mixed_vars[1])
## [1] "character"
class(mixed_vars[2])
## [1] "character"
class(mixed_vars[3])
## [1] "character"

four_seasons <- c("spring", "summer", "autumn", "winter")
my_favorite_season <- four_seasons == "autumn"
four_seasons[my_favorite_season]
## [1] "autumn"

four_seasons <- c("spring", "summer", "autumn", "winter")
my_favorite_seasons <- four_seasons == "spring" | four_seasons == "autumn" # 我喜歡春天或秋天
four_seasons[my_favorite_seasons]
## [1] "spring" "autumn"

rep() 函數可以生成重複變數的向量，times 參數可以指定要生成幾個：

rep(7L, times = 8)
## [1] 7 7 7 7 7 7 7 7
rep("R", times = 10)
##  [1] "R" "R" "R" "R" "R" "R" "R" "R" "R" "R"

seq() 函數可以生成等差數列，from 參數指定數列的起始值，to 參數指定數列的終止值，by 參數指定數值的間距：

seq(from = 7, to = 77, by = 7)
##  [1]  7 14 21 28 35 42 49 56 63 70 77
seq(from = 1, to = 10, by = 1)
##  [1]  1  2  3  4  5  6  7  8  9 10

1:10
##  [1]  1  2  3  4  5  6  7  8  9 10
11:20
##  [1] 11 12 13 14 15 16 17 18 19 20

## 10.3 因素向量

R 語言針對儲存文字的向量有一個特殊的資料結構稱為因素向量（factor），它是一個帶有層級（Levels）資訊的向量，我們使用 factor() 函數可以將向量轉換成因素向量：

four_seasons <- c("spring", "summer", "autumn", "winter")
four_seasons
## [1] "spring" "summer" "autumn" "winter"
four_seasons_factor <- factor(four_seasons)
four_seasons_factor
## [1] spring summer autumn winter
## Levels: autumn spring summer winter

four_seasons <- c("spring", "summer", "autumn", "winter")
four_seasons_factor <- factor(four_seasons, ordered = TRUE, levels = c("summer", "winter", "spring", "autumn"))
four_seasons_factor
## [1] spring summer autumn winter
## Levels: summer < winter < spring < autumn

temperatures <- c("warm", "hot", "cold")
temp_factors <- factor(temperatures, ordered = TRUE, levels = c("cold", "warm", "hot"))
temp_factors
## [1] warm hot  cold
## Levels: cold < warm < hot

temperatures <- c("warm", "hot", "cold")
temp_factors <- factor(temperatures, ordered = TRUE)
temp_factors
## [1] warm hot  cold
## Levels: cold < hot < warm