How to subset matrix to one column, maintain matrix data type, maintain row/column names?

RMatrixSubsetR Faq

R Problem Overview


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 ] )

R Solutions


Solution 1 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSurajView Question on Stackoverflow
Solution 1 - RJoshua UlrichView Answer on Stackoverflow