Keep column name when selecting one column from data / matrix frame in R

In R, when I select only one column from the data / matrix frame, the result will become a vector and lost the column names, how can I save the column names? For example, if I run the following code,

x <- matrix(1,3,3) colnames(x) <- c("test1","test2","test3") x[,1] 

I will get

 [1] 1 1 1 

Actually, I want to get

  test1 [1,] 1 [2,] 1 [3,] 1 

The following code gives me exactly what I want, however, is there an easier way to do this?

 x <- matrix(1,3,3) colnames(x) <- c("test1","test2","test3") y <- as.matrix(x[,1]) colnames(y) <- colnames(x)[1] y 
+7
r
source share
2 answers

Use the drop argument:

 > x <- matrix(1,3,3) > colnames(x) <- c("test1","test2","test3") > x[,1, drop = FALSE] test1 [1,] 1 [2,] 1 [3,] 1 
+16
source share

Another possibility is to use subset :

 > subset(x, select = 1) test1 [1,] 1 [2,] 1 [3,] 1 
+6
source share

All Articles