0

I have a large matrix from which I want to select rows to further process them. Ultimatly, I want to convert the matrix to a dataframe that only contains my rows of interest. The easiest thing would be to simple run something like data.frame(my_matrix)[c(3,5),]. The problem with this is, that I am working with a very big sparse matrix, so converting all of it to a dataframe just to select a few rows is ineffective.

This option does what I want, but somehow only returns the result that I intend if I indicate at least 2 indices.

m <- matrix(1:25,nrow = 5)
rownames(m) <- 1:5
colnames(m) <- c("A","B","C","D","E")

data.frame(m[c(3,5),])

If i only want to select 1 row, and if I use the code above, the result is not a "wide" dataframe, but instead a long one, which looks like this:

data.frame(m[c(2),])

  m.c.2....
A         2
B         7
C        12
D        17
E        22

Is there a simple way to get a dataframe with just one row out of the matrix without converting the whole matrix first? It feels like I am overlooking something very obvious here...

Any help is much appreciated!

nhaus
  • 786
  • 3
  • 13

1 Answers1

1

You need to use drop=FALSE in the matrix subset, otherwise it will turn the matrix into a vector, as you saw.

m <- matrix(1:25,nrow = 5)
rownames(m) <- 1:5
colnames(m) <- c("A","B","C","D","E")

data.frame(m[c(2),, drop=FALSE])
#>   A B  C  D  E
#> 2 2 7 12 17 22

Created on 2022-10-12 by the reprex package (v2.0.1)

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25