Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 809
SacHin DhiMan Avatar asked Apr 16 '13 08:04

SacHin DhiMan


People also ask

How do you denote columns and rows in a matrix?

The size of a matrix is defined by the number of rows and columns that it contains. A matrix with m rows and n columns is called an m × n matrix or m-by-n matrix, while m and n are called its dimensions. For example, the matrix A above is a 3 × 2 matrix.

Can you set row and column names in a matrix R or IML )?

You can assign names to the rows and columns of a matrix with the rownames and colnames functions.

How do you name columns in a matrix?

Using colnames() function To Rename Matrix Column We use colnames() function for renaming the matrix column in R. It is quite simple to use the colnames() function. If you want to know more about colnames() function, then you can get help about it in R Studio using the command help(colnames) or ? colnames().


2 Answers

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.

like image 116
Jilber Urbina Avatar answered Oct 01 '22 01:10

Jilber Urbina


To dynamically names columns (or rows) you can try

colnames(rmatrix) <- letters[1:ncol(rmatrix)]

where letters can be replaced by a vector of column names of your choice. You can do similar thing for rows.  

like image 43
CHP Avatar answered Oct 01 '22 03:10

CHP