0

Apparently some matrices when indexed in a certain way stay matrices, others, indexed in the same way become arrays. Example:

> test = matrix(1:10, nrow = 2)
> class(test)
[1] "matrix"
> class(test[,1:2])
[1] "matrix"
> test = matrix(1:10, nrow = 1)
> class(test)
[1] "matrix"
> class(test[,1:2])
[1] "integer"

I would like to know:

  1. Why is this a feature and not a bug?
  2. Is there a polished way to make it stay a matrix? (I mean, sure, I could store nrow(test) somewhere and then use matrix(test, nrow = somewhere)) but i hope that there's a neat one-liner for something that in principle should have worked authomatically.

P.S. Why I find this an issue? Because if I then transpose the vector with t() (the vector that lost the matrix structure) it gives me a row vector, I wanted a column vector, as it should have been in theory. Also, rowMeans() doesn't work anymore with that vector.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
ThePunisher
  • 206
  • 1
  • 7
  • 4
    Yes, when `[` applied to a matrix gets a single row or column back, the extra dimensions are silently "dropped" and it becomes a vector. This can be disabled by using the `drop = FALSE` argument. `class(test[, 1:2, drop = FALSE])`. – Gregor Thomas May 05 '21 at 13:53
  • 2
    Regarding 1: it *is* widely considered a bug (or at least a mistake), which is why e.g. ‘tibble’ explicitly breaks inheritance rules to change this behaviour in the `tibble` class which inherits from `data.frame`. – Konrad Rudolph May 05 '21 at 13:55
  • 1
    This is also one of the top answers in the old FAQ about [the biggest R "gotchas"](https://stackoverflow.com/a/1535231/903061) – Gregor Thomas May 05 '21 at 13:55

0 Answers0