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
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.
You can assign names to the rows and columns of a matrix with the rownames and colnames functions.
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().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With