20

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 
Henrik
  • 65,555
  • 14
  • 143
  • 159
SacHin DhiMan
  • 201
  • 1
  • 2
  • 4

3 Answers3

24

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.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • if I don not want a common prefix then? I mean col1 should UNIT, col2 should be RATE, col3 Should be PRICE. – Kuldeep Singh Feb 06 '17 at 12:04
  • @KuldeepSingh, you can simply use `colnames` this way `colnames(your.matrix.here) <- c("UNIT", "RATE", "PRICE")`, take a look at [`?colnames`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/colnames.html), there is also `rownames` for row naming. – Jilber Urbina Feb 06 '17 at 14:51
8

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.  

manotheshark
  • 4,297
  • 17
  • 30
CHP
  • 16,981
  • 4
  • 38
  • 57
5

You may use provideDimnames. Some examples with various degree of customisation:

m <- matrix(1:12, ncol = 3)

provideDimnames(m)
#   A B  C
# A 1 5  9
# B 2 6 10
# C 3 7 11
# D 4 8 12

provideDimnames(m, base = list(letters, LETTERS))
#   A B  C
# a 1 5  9
# b 2 6 10
# c 3 7 11
# d 4 8 12

provideDimnames(m, base = list(paste0("row_", letters), paste0("col_", letters)))
#       col_a col_b col_c
# row_a     1     5     9
# row_b     2     6    10
# row_c     3     7    11
# row_d     4     8    12
Henrik
  • 65,555
  • 14
  • 143
  • 159