Open In App

Naming Rows and Columns of a Matrix in R Programming – rownames() and colnames() Function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

rownames() function in R Language is used to set the names to rows of a matrix.

Syntax:
rownames(x) <- value

Parameters:
x: Matrix
value: Vector of names to be set

Example:




# R program to provide a name
# to rows of a Matrix
     
# Creating a 3X3 Matrix
A = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) 
  
# Calling rownames() Function
rownames(A) <- letters[1:3]
  
print(A) 


Output:

  [, 1] [, 2] [, 3]
a    1    2    3
b    4    5    6
c    7    8    9

colnames() Function

colnames() function in R Language is used to set the names to columns of a matrix.

Syntax:
colnames(x) <- value

Parameters:
x: Matrix
value: Vector of names to be set

Example:




# R program to provide a name
# to columns of a Matrix
     
# Creating a 3X3 Matrix
A = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) 
  
# Calling colnames() Function
colnames(A) <- letters[1:3]
  
print(A) 


Output:

      a    b    c
[1, ] 1    2    3
[2, ] 4    5    6
[3, ] 7    8    9


Last Updated : 05 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads