w3resource

How to Create a Matrix in R with Custom Column and Row names?

R Programming: Matrix Exercise-3 with Solution

Write a R program to create a matrix taking a given vector of numbers as input and define the column and row names. Display the matrix.

Sample Solution:

R Programming Code:

# Define the row names for the matrix
row_names = c("row1", "row2", "row3", "row4")

# Define the column names for the matrix
col_names = c("col1", "col2", "col3", "col4")

# Create a 4x4 matrix with numbers from 1 to 16, filled by rows, and assign row and column names
M = matrix(c(1:16), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))

# Print a message indicating the matrix is being displayed
print("Original Matrix:")

# Display the created matrix
print(M)

Output:

[1] "Original Matrix:"
     col1 col2 col3 col4
row1    1    2    3    4
row2    5    6    7    8
row3    9   10   11   12
row4   13   14   15   16                

Explanation:

  • Define row names: Creates a vector row_names containing four elements: "row1", "row2", "row3", and "row4".
  • Define column names: Creates a vector col_names containing four elements: "col1", "col2", "col3", and "col4".
  • Create a matrix: Uses the matrix() function to create a 4x4 matrix M filled with numbers from 1 to 16, arranged by rows. The matrix is given row and column names using the dimnames parameter.
  • Print a message: Displays the message "Original Matrix:" to indicate that the matrix will be printed next.
  • Display the matrix: Prints the created matrix M with the specified row and column names.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create a matrix taking a given vector of numbers as input. Display the matrix.
Next: Write a R program to access the element at 3rd column and 2nd row, only the 3rd row and only the 4th column of a given matrix.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/matrix/r-programming-matrix-exercise-3.php