1

I am trying to extract a sub-matrix of a larger matrix, containing only the first n rows:

> first.rows <- function(x, n) {
+   x[1:n,]
+ }
> x <- matrix(1:6, 3, 2)
> first.rows(x, 2)
     [,1] [,2]
[1,]    1    4
[2,]    2    5

The naive approach, shown above, works nicely unless n is less than two:

> first.rows(x, 1)
[1] 1 4

For n == 1, I suddenly get a vector and not a matrix! I can work around this by using matrix(x[1:n,], n, ncol(x)), but this looks unnecessarily convoluted. Is there a way to solve this problem without the matrix-vector-matrix round-trip? (Maybe even working for n == 0?)

jochen
  • 3,728
  • 2
  • 39
  • 49

1 Answers1

3

We need to use drop = FALSE for cases where there is only a single row as by default [ (please check ?Extract) it uses drop = TRUE unlike subset

first.rows <- function(x, n) {
   x[seq_len(n),, drop = FALSE]
}

In addition to that, it is better to have seq_len(n) instead of 1:n for special cases where one can have n=0

akrun
  • 874,273
  • 37
  • 540
  • 662