Can we Name the Rows & Columns in R Matrix?
Yes It is possible to name the rows and columns of the matrix during creation with the dimnames argument of the matrix () function
Let’s look at this below example:
Here I have assigned a Variable my_data to print elements from 1 to 5 and print the my_data
Each Column has a Name a, b,c,d,e for 1,2,3,4,5 values.
Let’s Work on few Functions in matrices:
1.names () function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix, or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named.
Syntax: names(x) <- value
Parameters:
x: Object i.e. vector, matrix, data frame, etc.
value: Names to be assigned to x
2.If you want to remove the naming:
Look at the lines 11 & 12 to clear the names of the Vectors/Matrices/Data Frames.
We can see the output here, the naming for the vector is removed.
3.rep () Function:
In simple terms, rep in R, or the rep () function replicate numeric values, or text, or the values of a vector for a specific number of times.
Will Quickly have a look at rep() Function example:
Here The three elements are printed thrice.
The same output can be printed using times () Function.
4.times () Function:
Here also we are getting the same output.
5. Each () function:
If you want the output to be printed Like this:
“Learn” “Learn” “Learn” “Matrix” “Matrix” “Matrix” “In R” “In R” “In R”
We can achieve this using each () function.
Here we can see the desired output.
5.Create a matrix with rep () function:
Now let us Name the rows and columns :
6. rownames ():
rownames() function in R Language is used to set the names to rows of a matrix.
Syntax:
rownames(x) <- valueParameters:
x: Matrix
value: Vector of names to be set
In this example: look at the lines 10 & 11 ,rownames() is the function used to name the rows, data is our matrix data and x,y,z are the names given to the rows.
Similarly we will be using the colnames() to name the columns.
7.Colnames():colnames() function in R Language is used to set the names to columns of a matrix.
In this example: look at the lines 13 & 14, colnames() is the function used to name the columns, data is our matrix data and A,B,C are the names given to the Columns.
8. from the same above example, if we want to change the value of the second row and second column from Matrix to Vectors.
The syntax will be like this:
data[“Y”,”B”] <- “Vectors”
As we can see that value is changed to vectors.
Will Illustrate Matrix Operations in my next Post…. Happy Coding 😊