★ R 的變數與資料
★ R 軟體的變數與資料
| R 軟體的變數種類 | R 軟體的資料屬性 |
|---|---|
| ► 向量 (vector) | ► logical (TRUE (T) or FALSE (F)) |
| ► 矩陣 (matrix) | ► integer (整數) |
| ► 陣列 (array) | ► double (雙倍精確度實數, 預設) |
| ► 因子 (factor) | ► complex (複數) |
| ► 資料框架 (data-frame) | ► character (文字字串) |
| ► 串列 (list) | ► raw (二進位資料) |
★ 向量變數 (vector)
用 c()
●函數將數個數字聯結在一起:
x = c(1, 3.1, 4, 6, 9); x
## [1] 1.0 3.1 4.0 6.0 9.0
1/x
## [1] 1.0000000 0.3225806 0.2500000 0.1666667 0.1111111
s=c(x,0,x);s
## [1] 1.0 3.1 4.0 6.0 9.0 0.0 1.0 3.1 4.0 6.0 9.0
●向量、矩陣、陣列中的元素可以是數值、字串、邏輯值, 但變數中所有元素需均為同一屬性
x=1:3
y=c("A","B")
c(x,y)
## [1] "1" "2" "3" "A" "B"
●聯結向量
1.c(): 聯結成較長向量
##用c()將3個向量串再一起
x=1:3;y=4:6;z=7:9
xyz1=c(x,y,z);xyz1
## [1] 1 2 3 4 5 6 7 8 9
2.rbind(): row bind 之意, 一列一列聯結成矩陣
xyz2=rbind(x,y,z);xyz2
## [,1] [,2] [,3]
## x 1 2 3
## y 4 5 6
## z 7 8 9
3.cbind(): column bind 之意, 一行一行聯結成矩陣
xyz3=cbind(x,y,z);xyz3
## x y z
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
★ 矩陣變數 (matrix)
●用matrix()建構矩陣:
matrix(data=NA,nrow=1,ncol=1,byrow=FALSE,dimnames=NULL)
Example; 1;建立5*4矩陣:
A = matrix(1:20, nrow=5, ncol=4); A
## [,1] [,2] [,3] [,4]
## [1,] 1 6 11 16
## [2,] 2 7 12 17
## [3,] 3 8 13 18
## [4,] 4 9 14 19
## [5,] 5 10 15 20
Example 2 : 將數字一列一列填入矩陣中(橫為列值為行)
##程式碼括弧內會多加byrow=T表示數據由列(橫)開始放
B = matrix(1:20, 5, 4, byrow=T); B
## [,1] [,2] [,3] [,4]
## [1,] 1 2 3 4
## [2,] 5 6 7 8
## [3,] 9 10 11 12
## [4,] 13 14 15 16
## [5,] 17 18 19 20
Example 3 : 3×5的 0 矩陣
D = matrix(0, 3, 5); D
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0 0 0 0 0
## [2,] 0 0 0 0 0
## [3,] 0 0 0 0 0
★設定列或行的名稱
列名rownames() 行名colnames() 維度名稱dimnames()
# 建立一個矩陣
A <- matrix(1:9, nrow = 3, byrow = TRUE);A
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9
# 設定列名
rownames(A) <- c("Row1", "Row2", "Row3")
# 設定欄名
colnames(A) <- c("Col1", "Col2", "Col3");A
## Col1 Col2 Col3
## Row1 1 2 3
## Row2 4 5 6
## Row3 7 8 9
dimnames()例子:
# 建立一個 2x3 的矩陣
A <- matrix(1:6, nrow = 2)
# 使用 dimnames() 為行名和列名設定名稱
dimnames(A) <- list(c("Row1", "Row2"), c("Col1", "Col2", "Col3"))
# 查看矩陣結果
A
## Col1 Col2 Col3
## Row1 1 3 5
## Row2 2 4 6
★ 陣列變數 (array)
array(data=NA,dim=length(data),dimnames=NULL)
●用 array()建構矩陣:
# 創建一個 2x3x2 的三維數組
a <- array(1:12, dim = c(2, 3, 2))
a
## , , 1
##
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
##
## , , 2
##
## [,1] [,2] [,3]
## [1,] 7 9 11
## [2,] 8 10 12
增加維度名稱:
# 設定維度名稱
dimnames(a) <- list(c("Row1", "Row2"), c("Col1", "Col2", "Col3"), c("Slice1", "Slice2"))
a
## , , Slice1
##
## Col1 Col2 Col3
## Row1 1 3 5
## Row2 2 4 6
##
## , , Slice2
##
## Col1 Col2 Col3
## Row1 7 9 11
## Row2 8 10 12
★ 因子(factor)變數
●factor 變數用來儲存類別型資料
●文字向量或數值向量均可用 factor() 轉成 factor 變數
# 創建一個因子
colors <- factor(c("Red", "Blue", "Green", "Blue", "Red", "Green", "Green"))
# 查看因子
colors
## [1] Red Blue Green Blue Red Green Green
## Levels: Blue Green Red