I would like to index-select a column from a matrix while keeping is colname. For example

m<-matrix(1:9,ncol=3)
colnames(m)<-c('V1','V2','V3')
selected<-as.matrix(m[,1])

However,

> selected
     [,1]
[1,]    1
[2,]    2
[3,]    3

I would like to have colname(selected)<-'V1' as a result instead. Why does R behave like this and how can I fix it? Thanks.

有帮助吗?

解决方案

Remove the as.matrix() in the last line and use drop=FALSE (see ?Extract)

> m<-matrix(1:9,ncol=3)
> colnames(m)<-c('V1','V2','V3')
> m[,1,drop=FALSE]
     V1
[1,]  1
[2,]  2
[3,]  3

What you do, is selecting a single column. R will by default drop all dimensions (and hence also the names) that are not necessary. In this case, you drop one dimension as a single column can be seen as a vector. The argument drop=FALSE prevents this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top