Keep column name when filtering matrix columns

I have a matrix similar to the one generated with this code:

> m = matrix(data=c(1:50), nrow= 10, ncol = 5); > colnames(m) = letters[1:5]; 

If I filter the columns and the result has more than one column, the new matrix saves the names. For example:

 > m[, colnames(m) != "a"]; bcde [1,] 11 21 31 41 [2,] 12 22 32 42 [3,] 13 23 33 43 [4,] 14 24 34 44 [5,] 15 25 35 45 [6,] 16 26 36 46 [7,] 17 27 37 47 [8,] 18 28 38 48 [9,] 19 29 39 49 [10,] 20 30 40 50 

Note that here the class is still the matrix:

 > class(m[, colnames(m) != "a"]); [1] "matrix" 

But, when the filter allows only one column, the result is a vector (an integer vector in this case) and the column name is lost.

 > m[, colnames(m) == "a"] [1] 1 2 3 4 5 6 7 8 9 10 > class(m[, colnames(m) == "a"]); [1] "integer" 

The name of the column is very important.

I would like to keep both the matrix structure (single column matrix) and the column name.

But the column name is more important.

I already know how to solve this a long way (tracking every case). I wonder if there is an elegant, enlightening solution.

+7
source share
2 answers

You need to set drop = FALSE . This is good practice for software use.

a fall

For matrices and arrays. If TRUE, the result is forced to the smallest possible size (see Examples)

 m[,'a',drop=FALSE] 

This will also save the names.

+13
source

You can also use subset :

 ma = subset(m, select = colnames(m) == "a") 
+3
source

All Articles