Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove column names from a matrix in R?

Tags:

r

matrix

  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?

like image 256
wolfsatthedoor Avatar asked Sep 18 '15 18:09

wolfsatthedoor


People also ask

How do I remove column names in R?

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.

How do I delete column names?

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.

How do you remove a column from a matrix?

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.


2 Answers

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.

like image 189
hmhensen Avatar answered Oct 05 '22 07:10

hmhensen


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.

like image 43
RHertel Avatar answered Oct 05 '22 08:10

RHertel