22
  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?

wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90
  • I don't get the desired output, I get NA NA NA rather than [,1] [,2] [,3] – wolfsatthedoor Sep 18 '15 at 18:36
  • The code does not work for you? It works fine for me...I am trying to get from a matrix with a ton of assigned names to a nameless one. The reason is complicated. This should be a fairly easy thing to do i'd think... – wolfsatthedoor Sep 18 '15 at 18:38

3 Answers3

27

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.

hmhensen
  • 2,974
  • 3
  • 22
  • 43
21

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.

RHertel
  • 23,412
  • 5
  • 38
  • 64
4

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
Fouad Selmane
  • 378
  • 2
  • 11