Why does $ not partially match on summaries of linear models?

Viewed 43

Take summary(lm(wt~mpg,data=mtcars))->a. a$r returns NULL, suggesting that there were no variables names beginning with r. However, both a$residuals and a$r.squared give valid output, contradicting this premise. What is my misunderstanding of the $ operator? I thought that it always partially matched.

1 Answers

There's a clue in ?pmatch (which is referenced in ?$ in passing).

nomatch: the value to be returned at non-matching or multiply partially matching positions.

In the case of pmatch it's NA_integer_, but in the case of $ I guess it's NULL (I don't really want to go rooting around that deep in the R source code to confirm).

More specifically, the "Indexing by vectors" section of the R language manual says

x$aa will match x$aabb if x does not contain a component named "aa" and "aabb" is the only name which has prefix "aa".

It doesn't say explicitly that NULL is returned otherwise, but that's generally what you get when there is no match (e.g. a$junk).

At a more abstract level, it's hard to think of an unsurprising/principled/non-dangerous way to resolve the ambiguity when there are multiple partial matches: pick the first alphabetical one (which could be different depending on locale etc.)? Pick the one with the lowest numerical index?

Related