我有这个矩阵:
[,1] [,2]
[1,] 0 0
[2,] 0 0
[3,] 0 1
[4,] 1 0
[5,] 3 2
[6,] 4 0
[7,] 0 0
[8,] 0 0
[9,] 4 5
[10,] 0 3
我想像这样的数字添加rownames:
[,1] [,2]
1 0 0
2 0 0
3 0 1
4 1 0
5 3 2
6 4 0
7 0 0
8 0 0
9 4 5
10 0 3
我是手动完成的,但如果我的行数太多,那么我需要花费太长时间。是否有其他更短的方法将行索引添加为rownames?
以下是代码:
mat=matrix(c(0,0,0,1,3,4,0,0,4,0,0,0,1,0,2,0,0,0,5,3), ncol=2)
mat
rownames(mat)=c("1","2","3","4","5","6","7","8","9","10")
答案 0 :(得分:2)
对于非常大的矩阵,我可以推荐优化原语:seq_len()
。你在这里做
rownames(mat) <- seq_len(nrow(mat))