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