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?
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.
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
.
If you want to delete row names use row.names()
function
>M
a b c
1[1,] 1 4 7
2[2,] 2 5 8
3[3,] 3 6 9
>row.names(M)<- NULL ; colnames(M)<- NULL
>M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.