Home > Software engineering >  Why R is returning object when names are partially matching?
Why R is returning object when names are partially matching?

Time:10-06

Let say I have below list

Dat = list('AAA' = 1:4, 'BBB' = 5:9)

Now I have below syntax

Dat$AA
## [1] 1 2 3 4

However my question in why R is retuning value from Dat$AA given that there is no element with such name? Is R returning partial names?

If this is the case, then I think such behaviour is utterly risky and should not be allowed.

CodePudding user response:

According to ?Extract

Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]]. Also, the partial matching behavior of [[ can be controlled using the exact argument.

Also, it is written under name

name - A literal character string or a name (possibly backtick quoted). For extraction, this is normally (see under ‘Environments’) partially matched to the names of the object.

where the usage is

x$name


As the exact is FALSE, it allows for partial matching when we use $. It is one of the reasons to use [[ where the exact = TRUE as the usage is

x[[i, exact = TRUE]]

It is also mentioned in ?Extract how to change the options

Thus the default behaviour is to use partial matching only when extracting from recursive objects (except environments) by $. Even in that case, warnings can be switched on by options(warnPartialMatchDollar = TRUE).

CodePudding user response:

akrun already explained that this behaviour is documented, but generally we prefer that this doesn't happen. Consequently, a set of lines that I always put into my .Rprofile is the following:

options(
  warnPartialMatchArgs = TRUE,
  warnPartialMatchDollar = TRUE,
  warnPartialMatchAttr = TRUE
)

This will be run when R starts, and generate warnings whenever partial matching occurs in R. There are three contexts that it happens as shown: in function arguments, when using $, and in using attr(). I don't think you can turn the partial matching off entirely, but this should highlight whenever it happens and prevent ensuing bugs.

  • Related