我有一个矩阵:
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) 不起作用。
[
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
尝试使用“names”而不是“colnames”
names (d)
[1] "a"