M = matrix(1:9,3,3)
colnames(M)=c('a','b','c')
Suppose I have a matrix M
, with column names 'a','b','c'. And I want to remove the names, so that M
M [,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
Rather than
a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
How do I do this?
Data Visualization using R Programming To remove the row names or column names from a matrix, we just need to set them to NULL, in this way all the names will be nullified.
Right-click the column you want to delete and choose Delete Column from the shortcut menu. If the column participates in a relationship (FOREIGN KEY or PRIMARY KEY), a message prompts you to confirm the deletion of the selected columns and their relationships. Choose Yes.
The easiest way to remove a row or column from a matrix is to set that row or column equal to a pair of empty square brackets [] . For example, create a 4-by-4 matrix and remove the second row. Now remove the third column.
I know it's been a while since this was asked, but seeing as it is a highly trafficked question, I thought this might be useful.
If you want to perform this action on M
instead of its column names, you could try
M <- unname(M)
>M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
This would be more efficient if you want to pipe or nest the output into subsequent functions because colnames
does not return M
.
You can try
colnames(M) <- NULL
Using your example:
> M
# a b c
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9
> colnames(M) <- NULL
> M
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9
However, if your data is stored in a data.frame instead of a matrix, this won't work. As explained in ?data.frame
:
The column names should be non-empty, and attempts to use empty names will have unsupported results
If your data is stored as a data.frame (this can be checked with class(my_data)
), you could try to convert it into a matrix with M <- as.matrix(my_data)
. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With