Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to drop=FALSE or changing default behavior [duplicate]

Tags:

r

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.

like image 973
hedgedandlevered Avatar asked Apr 08 '13 19:04

hedgedandlevered


1 Answers

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.

like image 170
MvG Avatar answered Oct 22 '22 15:10

MvG