When working with named vectors like
vec <- c(a = 1, b = 2)
I often find myself introducing mistakes by writing vec$a
when I should be writing vec["a"]
or vec[["a"]]
to access the corresponding value with and without the name, respectively.
I think vec$a
being an error is counter-intuitive, as $
generally extracts named things. This feeling even seems supported e.g. in ?Extract
, where the example usage is x$name
- isn't that a perfect fit for a named vector?
That got me thinking about the possibility of overloading the $
operator to work on named vectors. However, I am not very experienced with operator overloading in R, and I understand (e.g. from the answers here) that caution is advised when overloading basic operators.
My interconnected questions: Is there a reason why I shouldn't overload $
as described that I'm failing to understand? That is, is there (in some vague sense) a "good" reason why this is not the default in R? If not, how might I sensibly do so?
I understand that in practice this is likely a bad idea, if only for reasons of portability, but I'm still curious.