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.