如何从R中的矩阵中删除列名? [英] How to remove column names from a matrix in R?
问题描述
M = matrix(1:9,3,3)
colnames(M)=c('a','b','c')
假设我有一个矩阵M
,其列名为'a','b','c'.我想删除名称,以便M
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
而不是
a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
我该怎么做?
推荐答案
您可以尝试
colnames(M) <- NULL
使用您的示例:
> 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
但是,如果您的数据存储在data.frame中而不是矩阵中,则将无法使用.如?data.frame
中所述:
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
如果您的数据存储为data.frame(可以使用class(my_data)
进行检查),则可以尝试使用M <- as.matrix(my_data)
将其转换为矩阵.希望这会有所帮助.
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.
这篇关于如何从R中的矩阵中删除列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!