1. 程式人生 > >2-3 R語言基礎 矩陣和數組

2-3 R語言基礎 矩陣和數組

not 方法 ttr error bind names cbi 向量 bin

#矩陣Matrix 三個參數:內容(可省),行數,列數

> x <- matrix(1:6,nrow = 3,ncol = 2) #第一個是內容,第二個,第三個是行列
> x[1,2]
[1] 4


> #維度屬性
> dim(x)
[1] 3 2


> #查看矩陣的屬性
> attributes(x)
$`dim`
[1] 3 2

> #由向量來創建矩陣的方法
> y <-1:6
> dim(y) <- c(2,3)
> dim(y)
[1] 2 3


> y2 <- matrix(1:6,nrow = 2,ncol = 3)
> y2
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6


> rbind(y,y2) #列相同,按行拼接
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[3,] 1 3 5
[4,] 2 4 6


> cbind(y,y2) #行相同,按列拼接
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 3 5 1 3 5
[2,] 2 4 6 2 4 6


> #使用列表給矩陣的行列命名
> dimnames(x) <- list(c("a", "b"),c("c", "d", "e"))
Error in dimnames(x) <- list(c("a", "b"), c("c", "d", "e")) :
length of ‘dimnames‘ [1] not equal to array extent
> x
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6

2-3 R語言基礎 矩陣和數組