The default behavior in R for reducing a 2 dimensional matrix to 1 row is to actually drop a dimension. This can be "fixed" by putting drop=FALSE at the end of the matrix search. Is there a way to make this the default? I have a pretty long program and just realized I'm going to have to add this in about 100 places if there isn't... I searched ?options, ?'[', and ?matrix to no avail.
You can redefine `[`
like this:
old <- `[`
`[` <- function(...) { old(..., drop=FALSE) }
This modification should be local to the interactive scope and therefore not affect routines which rely on the other behaviour. No guarantees, though. And be prepared that code of this form will be likely to confuse readers of your code, who are used to the other semantics.
Perhaps you can make this change local to a specific function, instead of all your code?
One alternative would be writing your own class for the matrix objects, for which you can provide your own subset operator implementation. This makes sense if you construct matrices in a very limited number of places, but might be a problem if there is a large number of code paths constructing these matrices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With