2

Possible Duplicate:
1-dimensional Matrix is changed to a vector in R

I work with matrix objects in R and many times it happens that I want to select only one column of a matrix a use it as a matrix of one column !!! Yes, I mean I don't want R to coerce it automatically to a numeric class because the meaning is a matrix of 1 column in that case. How to avoid R doing this silly conversion all the time at a general level. I don't want to clutter my code with as.matrix everywhere !

Community
  • 1
  • 1
David Bellot
  • 643
  • 7
  • 13
  • 1
    Sounds a like a read of the R Inferno is in order: http://www.burns-stat.com/pages/Tutor/R_inferno.pdf You're currently in Circle 8.1.44. – Aaron left Stack Overflow Oct 08 '12 at 19:21
  • @GSee: A quick search turned up: http://stackoverflow.com/q/9949202/892313, http://stackoverflow.com/q/12601692/892313, http://stackoverflow.com/q/7598674/892313. The first or the third would be the closest duplicate, I think. – Brian Diggs Oct 08 '12 at 19:27
  • https://stat.ethz.ch/pipermail/r-help/2009-November/218081.html – Ben Bolker Oct 08 '12 at 19:28
  • you guys are better than me at finding duplicate AND henceforth giving to me the answer. So, many thanks to all of you. – David Bellot Oct 09 '12 at 07:58

1 Answers1

4

Use drop=FALSE

> matrix(1:10, ncol=2)
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10
> matrix(1:10, ncol=2)[, 2]
[1]  6  7  8  9 10
> matrix(1:10, ncol=2)[, 2, drop=FALSE]
     [,1]
[1,]    6
[2,]    7
[3,]    8
[4,]    9
[5,]   10
GSee
  • 48,880
  • 13
  • 125
  • 145