102

When I subset a matrix to a single column, the result is of class numeric, not matrix (i.e. myMatrix[ , 5 ] to subset to the fifth column). Is there a compact way to subset to a single column, maintain the matrix format, and maintain the row/column names without doing something complicated like:

matrix( myMatrix[ , 5 ] , dimnames = list( rownames( myMatrix ) , colnames( myMatrix )[ 5 ] )
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Suraj
  • 35,905
  • 47
  • 139
  • 250

1 Answers1

145

Use the drop=FALSE argument to [.

m <- matrix(1:10,5,2)
rownames(m) <- 1:5
colnames(m) <- 1:2
m[,1]             # vector
m[,1,drop=FALSE]  # matrix
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • I would have sworn I saw this just recently but it may have been the analogous dataframe behavior that was being questioned: http://stackoverflow.com/questions/6941985/r-how-to-subset-a-data-frame-in-a-list-and-return-data-frame – IRTFM Sep 08 '11 at 17:59
  • 5
    If you want to index by only the first dimension, can you use drop as follows: `m[1,,drop=FALSE]` – Kevin Bullaughey Nov 26 '14 at 03:58
  • To give an example on statistical grounds, using Cooks' D distances, and then selecting values based on a cut off value e.g. 0.1, it will result the cooksD values with their respective number of row in the relative dataset `cooksd<-as.data.frame(cooks.distance(ft1)) cooksD_outliers<-cooksd[cooksd>0.1,drop=FALSE,]` – Estatistics May 26 '17 at 14:23
  • result<-apply(temp,1,function(x) tapply(x, genesymbol,function(x) mean(x,na.rm=T))) How to deal with the problem that result is a array, but actually, I want it to be a one column data frame ? Thanks – Shicheng Guo Mar 08 '19 at 06:34
  • @ShichengGuo: You should ask a new question. – Joshua Ulrich Mar 08 '19 at 11:46
  • How would I get this from the documentation? I can't search `?[` – irritable_phd_syndrome Jun 27 '20 at 02:44
  • 1
    @irritable_phd_syndrom use `help("[")` or `?"["`. You need to quote any name that isn't "syntactic" (see `?Quotes` and `?Syntax` for details). – Joshua Ulrich Jun 27 '20 at 15:55
  • Interestingly, this doesn't seem to work if the object is sticky (package). – Sonia Mar 09 '23 at 16:24