1.获取矩阵的行数和列数,A为矩阵
nrow(A)#行数
ncol(A)#列数
2.如何获取矩阵每行或每列的最大值相对应的索引,A 为矩阵
dimnames(A) <- list(1:nrow(A), 1:ncol(A))
apply(A, 1, function(t) rownames(A)[which.max(t)])#每行最大值所对应的索引
apply(A, 2, function(t) colnames(A)[which.max(t)])#每行最大值所对应的索引
as.numeric(A)#将字符转换为数值型
3.如何由向量扩展成某行或某列相等的矩阵?
> b=c(1,2,3,4)
> matrix(rep(b),nrow=10,4,byrow=TRUE)#按行优先
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
[3,] 1 2 3 4
[4,] 1 2 3 4
[5,] 1 2 3 4
[6,] 1 2 3 4
[7,] 1 2 3 4
[8,] 1 2 3 4
[9,] 1 2 3 4
[10,] 1 2 3 4
默认是按列优先
> matrix(rep(b),nrow=4,10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 1 1 1 1 1 1 1 1
[2,] 2 2 2 2 2 2 2 2 2 2
[3,] 3 3 3 3 3 3 3 3 3 3
[4,] 4 4 4 4 4 4 4 4 4 4
4.有时候需要使用矩阵运算,那么如何将list 类型转换成matrix呢?
e<-unlist(preinputValue)#preinputValue是想要转换的对象
names(e)<-NULL
preinputValue = matrix(e,nrow= 1)
5.list之间可以相减,matrix之间可以相减,list与matrix之间不能相减