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
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.Next you’ll need to maintain the dimensions when subsetting; by default R will drop empty dimensions, which in the case of
vmabove is the row dimension. You do that usingdrop = FALSEin the call to'['(). The behaviour by default isdrop = TRUE:You could add a class to your matrices and write methods for
[for that class where the argumentdropis set toFALSEby defaultwhich in use gives:
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.