2-3 R语言基础 矩阵和数组

#矩阵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

posted @ 2018-11-11 14:56  hank-li  阅读(592)  评论(0编辑  收藏  举报