How can I make processing of matrices and vectors regular (as, e.g., in Matlab)

matrix, r, vector

Solution

In R, it is the other way round; matrices are vectors. The matrix-like behaviour comes from some extra attributes on top of the atomic vector part of the object.

To get the behaviour you want, you'd need to make the vector be a matrix, by setting dimensions on the vector using `dim()` or explicit coercion.

> vm <- 1:5
> dim(vm) <- c(1,5)
> vm
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
> class(vm)
[1] "matrix"

Next you'll need to maintain the dimensions when subsetting; by default R will drop empty dimensions, which in the case of `vm` above is the row dimension. You do that using `drop = FALSE` in the call to `'['()`. The behaviour by default is `drop = TRUE`:

> vm[, 2:4]
[1] 2 3 4
> vm[, 2:4, drop = FALSE]
     [,1] [,2] [,3]
[1,]    2    3    4

You could add a class to your matrices and write methods for `[` for that class where the argument `drop` is set to `FALSE` by default

class(vm) <- c("foo", class(vm))
`[.foo` <- function(x, i, j, ..., drop = FALSE) {
  clx <- class(x)
  class(x) <- clx[clx != "foo"]
  x[i, j, ..., drop = drop]
}

which in use gives:

> vm[, 2:4]
     [,1] [,2] [,3]
[1,]    2    3    4

i.e. maintains the empty dimension.

Making this fool-proof and pervasive will require a lot more effort but the above will get you started.

Problem

Suppose I have a function that takes an argument x of dimension 1 or 2. I'd like to do something like ``` x[1, i] ``` regardless of whether I got a vector or a matrix (or a table of one variable, or two). For example: ``` x = 1:5 x[1,2] # this won't work... ``` Of course I can check to see which class was given as an argument, or force the argument to be a matrix, but I'd rather not do that. In Matlab, for example, vectors are matrices with all but one dimension of size 1 (and can be treated as either row or column, etc.). This makes code nice and regular. Also, does anyone have an idea why in R vectors (or in general one dimensional objects) aren't special cases of matrices (or multidimensional objects)? Thanks

Original source