How to multiply a matrix into a single column, save the matrix data type, support row / column names?

When I multiply the matrix by one column, the result has a numeric number, not a matrix (for example, myMatrix [, 5] for a subset of the fifth column). Is there a compact way to subset to a single column, support matrix format and support row / column names without doing anything complicated, like this:

matrix( myMatrix[ , 5 ] , dimnames = list( rownames( myMatrix ) , colnames( myMatrix )[ 5 ] ) 
+63
source share
2 answers

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 
+89
source

For data.frame (a question marked as a duplicate of this question, although these questions are not duplicates), a neat way with dplyr is:

 mtcars %>% dplyr::select("wt") 
0
source

All Articles