R语言矩阵(matrix)详解

来源:互联网 发布:网络翻墙 违法 编辑:程序博客网 时间:2024/05/22 01:57
数据:
1 3 9 8 9 80 1
4 2 7 88 1 22 21

31 2 44 9 10 9 10


使用矩阵表示
1)向量转化为矩阵c—>matrix
tmp_matrix<-matrix(c(1,3,9,8,9,80,1,4,2,7,88,1,22,21,31,2,44,9,10,9,10),nrow=3,ncol=7,byrow=TRUE)
tmp_matrix<-matrix(c(1,3,9,8,9,80,1,4,2,7,88,1,22,21,31,2,44,9,10,9,10),ncol=7,byrow=TRUE)
tmp_matrix<-matrix(c(1,3,9,8,9,80,1,4,2,7,88,1,22,21,31,2,44,9,10,9,10),nrow=3,byrow=TRUE)
或者
tmp_matrix<-matrix(c(1,4,31,3,2,2,9,7,44,8,88,9,9,1,10,80,22,9,1,21,10),nrow=3,ncol=7,byrow=FALSE)
tmp_matrix<-matrix(c(1,4,31,3,2,2,9,7,44,8,88,9,9,1,10,80,22,9,1,21,10),nrow=3)
tmp_matrix<-matrix(c(1,4,31,3,2,2,9,7,44,8,88,9,9,1,10,80,22,9,1,21,10),ncol=7)—–建议使用
数据:
col1 col2 col3 col4 col5 col6 col7
row1 1 3 9 8 9 80 1
row2 4 2 7 88 1 22 21

row3 31 2 44 9 10 9 10


2)为矩阵添加名称dimnames参数
tmp_matrix<-matrix(c(1,4,31,3,2,2,9,7,44,8,88,9,9,1,10,80,22,9,1,21,10),ncol=7,dimnames=list(c(“row1″,”row2″,”row3″),c
(“col1″,”col2″,”col3″,”col4″,”col5″,”col6″,”col7″)))
或者
rownames(tmp_matrix)<-c(“row1″,”row2″,”row3″)
colnames(tmp_matrix)<-c(“col1″,”col2″,”col3″,”col4″,”col5″,”col6″,”col7″)
读取数据-无dimnames
行数据
tmp_matrix[1,]是向量: 1,3,9,8,9,80,1
tmp_matrix[2,]是向量: 4,2,7,88,1,22,21
tmp_matrix[3,]是向量: 31,2,44,9,10,9,10
列数据
tmp_matrix[,1]是向量: 1,4,31
tmp_matrix[,2]是向量: 3,2,2
tmp_matrix[,3]是向量: 9,7,44
tmp_matrix[,4]是向量: 8,88,9
tmp_matrix[,5]是向量: 9,1,10
tmp_matrix[,6]是向量: 80,22,9
tmp_matrix[,7]是向量: 1,21,10
点数据
tmp_matrix[i,j]是数据:i行j列的数据
读取数据-有dimnames
行数据
tmp_matrix[1,]和tmp_matrix["row1",]是第1行的向量
列数据
tmp_matrix[,1]和tmp_matrix[,"col1"]是第1列的向量
点数据
tmp_matrix[1,2]和tmp_matrix["row1","col2"]是第1行第2列的向量
读取名称
>dimnames(tmp_matrix)#是list
[[1]]
[1] “row1″ “row2″ “row3″
[[2]]
[1] “col1″ “col2″ “col3″ “col4″ “col5″ “col6″ “col7″
> rownames(tmp_matrix)#是向量
[1] “row1″ “row2″ “row3″
> colnames(tmp_matrix)#是向量
[1] “col1″ “col2″ “col3″ “col4″ “col5″ “col6″ “col7″
> rownames(tmp_matrix)[2]
[1] “row2″
> colnames(tmp_matrix)[4]
[1] “col4″
 
空矩阵
a<-matrix(0,nrow=12,ncol=11)
矩阵扩展
扩展列
>cbind(tmp_matrix,c(1,1,2))
col1 col2 col3 col4 col5 col6 col7
row1 1 3 9 8 9 80 1 1
row2 4 2 7 88 1 22 21 1
row3 31 2 44 9 10 9 10 2
扩展行
>rbind(tmp_matrix,c(1,1,2,2,1,1,9))
col1 col2 col3 col4 col5 col6 col7
row1 1 3 9 8 9 80 1
row2 4 2 7 88 1 22 21
row3 31 2 44 9 10 9 10
1 1 2 2 1 1 9
矩阵变为向量
>as.vector(tmp_matrix)#依据列方式
[1] 1 4 31 3 2 2 9 7 44 8 88 9 9 1 10 80 22 9 1 21 10
 
数据内部的数据类型
> tmp_matrix<-matrix(c(1,1,31,3,2,2,9,1,44,8,88,9,9,1,10,80,22,9,1,21,10),ncol=7)
> tmp_matrix
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 3 9 8 9 80 1
[2,] 1 2 1 88 1 22 21
[3,] 31 2 44 9 10 9 10
> tmp_matrix<-matrix(c(1,”4sssss”,31,3,2,2,9,”7aaaaaa”,44,8,88,9,9,1,10,80,22,9,1,21,10),ncol=7)
> tmp_matrix
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] “1″ “3″ “9″ “8″ “9″ “80″ “1″
[2,] “4sssss” “2″ “7aaaaaa” “88″ “1″ “22″ “21″
[3,] “31″ “2″ “44″ “9″ “10″ “9″ “10″
当改变一个数据为字符时候(“xxx”),其余数据全部改变了字符类型。
0 0
原创粉丝点击