Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

r - How to set unique row and column names of a matrix when its dimension is unknown?

I have matrix like :

     [,1][,2][,3][,4]
[1,]  12  32  43  55
[2,]  54  54  7   8
[3,]  2   56  76  88
[4,]  58  99  93  34

I do not know in advance how many rows and columns I will have in matrix. Thus, I need to create row and column names dynamically.

I can name columns (row) directly like:

colnames(rmatrix) <- c("a", "b", "c", "d")

However, how can I create my names vector dynamically to fit the dimensions of the matrix?

nm <- ("a", "b", "c", "d")
colnames(rmatrix) <- nm 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use rownames and colnames and setting do.NULL=FALSE in order to create names dynamically, as in:

set.seed(1)
rmatrix  <-  matrix(sample(0:100, 16), ncol=4)

dimnames(rmatrix) <- list(rownames(rmatrix, do.NULL = FALSE, prefix = "row"),
                          colnames(rmatrix, do.NULL = FALSE, prefix = "col"))

rmatrix
     col1 col2 col3 col4
row1   26   19   58   61
row2   37   86    5   33
row3   56   97   18   66
row4   89   62   15   42

you can change prefix to name the rows/cols as you want to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...