This got me pretty bad. You can abbreviate list names? I never noticed it before and I got totally screwed for like a day. Can someone explain what is happening here and why it could be more useful than it is terrible? And why its inconsistent like that at the bottom? And if I can turn it off?
> wtf <- list(whatisthe=1, pointofthis=2)
> wtf$whatisthe
[1] 1
> wtf$what
[1] 1
> wtf <- list(whatisthe=1, whatisthepointofthis=2)
> wtf$whatisthepointofthis
[1] 2
> wtf$whatisthep
[1] 2
> wtf$whatisthe
[1] 1
> wtf$what
NULL
I suspect that partial matching by the $
operator was a nice(r) feature for interactive use back in the days before tabbed completion had been implemented
If you don't like that behavior, you can use the "[["
operator instead.
It takes an argument exact=
, which allows you to control partial matching behavior, and which defaults to TRUE
.
wtf[["whatisthep"]] # Only returns exact matches
# NULL
wtf[["whatisthep", exact=FALSE]] # Returns partial matches without warning
# [1] 2
wtf[["whatisthep", exact=NA]] # Returns partial matches & warns that it did
# [1] 2
# Warning message:
# In wtf[["whatisthep", exact = NA]] :
# partial match of 'whatisthep' to 'whatisthepointofthis'
(This is one reason why "[["
is generally preferred to $
in R programming. Another is the ability to do this X <- "whatisthe"; wtf[[X]]
but not this X <- "whatisthe"; wtf$X
.)
For list element names (and function parameter names), R applies the following algorithm:
If there is an exact match for the item, use it. If there is not an exact match, look for partial matches. If there is exactly one partial match, use it. Otherwise, use nothing.