Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

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

1 Answer

0 votes
by
edited by

You can use the drop = FALSE argument to keep the data type as “matrix”.i.e.,

m <- matrix(1:10,5,2)

rownames(m) <- 1:5

colnames(m) <- 1:2

 m[,1]      

1 2 3 4 5 

1 2 3 4 5 

class(m[,1])

[1] "integer"

 m[,1,drop=FALSE]

  1

1 1

2 2

3 3

4 4

5 5

 class(m[,1,drop=FALSE])

[1] "matrix"

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...