Array, Matrices & Data Frames
Array
就是一般程式設計中的陣列,初始化一個矩陣的方法:
array(data = NA, dim = length(data), dimnames = NULL)
data
帶data要填滿array的vector。dim
帶有維度資訊的vector。dimnames
對維度命名的list,不常用。
> x <- array(rnorm(12), c(2,2,3))
> x
, , 1
[,1] [,2]
[1,] -0.5194684 -1.082588
[2,] -1.0341688 1.910179
, , 2
[,1] [,2]
[1,] -1.1380869 -0.6252769
[2,] -0.1237467 0.1439241
, , 3
[,1] [,2]
[1,] -1.227034 1.377770
[2,] -1.190919 -1.220666
Matrices
矩陣是帶有dimension屬性的vector,初始化一個矩陣的方式:
初始化一個矩陣
matrix([data, ]nrow = ?, ncol = ?)
data可以是array或1:10之類的integer slide,以column為單位(column-wise)按照順序填滿。
> x <- matrix(nrow = 2, ncol = 3) > x [,1] [,2] [,3] [1,] NA NA NA [2,] NA NA NA
給予vector維度屬性
dim(v) <- c(nrow, ncol)
取得dim屬性並賦值,ncol*nrow必須要等於元素個數。
> x <- 1:12 > x [1] 1 2 3 4 5 6 7 8 9 10 11 12 > dim(x) <- c(3, 4) > x [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12
Column/Row-binding
cbind(x, y)、rbind(x, y)將等長的陣列x、y作為column或row結合成matrixces。
> x <- 1:5 > y <- 6:10 #========================== #把vector看作為一行一行結合起來 > cbind(x, y) x y [1,] 1 6 [2,] 2 7 [3,] 3 8 [4,] 4 9 [5,] 5 10 #========================== #把vector看作為一列一列結合起來 > rbind(x, y) [,1] [,2] [,3] [,4] [,5] x 1 2 3 4 5 y 6 7 8 9 10
Data Frames
R用Data frame來儲存表格,Data frame可視為一種每個element都等長的list,每個element像是一個column,而element的大小就是表格的row number,因此Data frame內不同column可儲存不同資料類型(=每個element可各儲存一種資料類型),而Matrices不行,dplyr package提供方便操作Data frame的函式。
初始化的方法:
- 賦值初始化:
data.frame()
- 從檔案讀取表格,回傳data frame:
read.table()
、read.csv()
。
相關函式:
nrow()
、ncol()
、colnames()
、rownames()
不需要解釋。data.matrix()
把data frame轉成matrix。
#做一個data frame x
> x <- data.frame(foo = 1:4, bar = c("a", "b", "c", "d"))
> x
foo bar
1 1 a
2 2 b
3 3 c
4 4 d
#===========================
#取得行列數量
> nrow(x)
[1] 4
> ncol(x)
[1] 2
> dim(x)
[1] 4 2
#===========================
#取得行列的名稱
> colnames(x)
[1] "foo" "bar"
> rownames(x)
[1] "1" "2" "3" "4"
> dimnames(x)
[[1]]
[1] "1" "2" "3" "4"
[[2]]
[1] "foo" "bar"
#===========================
#把x轉成matrix,可以看到R把a-d標記為1-4作為轉換。
>data.matrix(x)
foo bar
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4