# How to Set Row and Column Names for a Matrix in R

### 04.11.2021

When working with matrices, you often want to use column and row names for readability. In this article, we will learn how to set row and column names for a Matrix in R.

Let's say we have some sales data of different campaigns. The rows are the campaigns and the columns will be the impressions, clicks, purchases respectively. We can start with the following matrix.

data.vec = c(100, 10, 2, 400, 20, 2, 400, 10, 2)

mat = matrix(data.vec, 3, 3, byrow=TRUE)
mat

# 		[,1] [,2] [,3]
# [1,]  100   10    2
# [2,]  400   20    2
# [3,]  600   12    3

Notice, that the matrix is a bit hard to understand as we don't have column or row names. Let's first clean this up by adding column names. We can do this using the colnames function.

colnames(mat) = c("Impressions", "Clicks", "Purchases")
mat

#		 Impressions Clicks Purchases
# [1,]         100     10         2
# [2,]         400     20         2
# [3,]         600     12         3

We can pass the matrix to the colnames function then assign a vector which is the list of our columns. As you can see above, the matrix is much easier to read.

Now, let's clean up the row names by adding the different campaigns. Let's say we had three campaigns Facebook, Google, Twitter. Similar to above, we can use the rownames function to assign the campaign names.

rownames(mat) = c("Facebook", "Google", "Twitter")
mat

# 			 Impressions Clicks Purchases
# Twitter          600     12         3