2

我有一个矩阵:

a<-c(0,1,3,5,56,3)
b<-c(1,4,3,10,3,50)
c<-cbind(a,b)
c<-as.matrix(c)

然后我创建了一个 c 的子集:

d<-c[1,1]

我想获得 d 的列名。colnames(d) 不起作用。

4

2 回答 2

8

[ will drop dimensions by default when possible, which here causes the structure to change from a matrix to a vector. Disable this behavior:

x <- cbind(a,b)
d <- x[1,1,drop=FALSE]

> colnames(d)
[1] "a"

Note that you didn't lose the names. They just were no longer column names:

d <- x[1,1]
names(d)
[1] "a"

In the case where you have row and column names, and use the default of drop=TRUE while choosing a single element, names will not be present in the result. R can't know whether you want to retain row or column names.

rownames(x) <- letters[7:12]
names(x[1,1])
NULL
于 2012-12-21T22:58:48.413 回答
0

尝试使用“names”而不是“colnames”

names (d)

[1] "a"
于 2012-12-22T16:32:07.147 回答