Empiromancer
Empiromancer

Reputation: 3854

What's wrong with using $-extraction?

fortune(312) and fortune(343) allude to the problems with using $ to extract elements of a list instead of [[, but aren't specific about what exactly the dangers are.

The problem here is that the $ notation is a magical shortcut and like any other magic
if used incorrectly is likely to do the programmatic equivalent of turning yourself into 
a toad.
   -- Greg Snow (in response to a user that wanted to access a column whose name is stored 
      in y via x$y rather than x[[y]])
      R-help (February 2012)

Sooner or later most R beginners are bitten by this all too convenient shortcut. As an R 
newbie, think of R as your bank account: overuse of $-extraction can lead to undesirable 
consequences. It's best to acquire the '[[' and '[' habit early.
   -- Peter Ehlers (about the use of $-extraction)
      R-help (March 2013)

Looking through the documentation for `$`, I've found that

$ is only valid for recursive objects

and

The main difference is that $ does not allow computed indices, whereas [[ does [...] Also, the partial matching behavior of [[ can be controlled using the exact argument.

So, is the argument to use [[ over $ because the former offers greater control and transparency in writing code? What are the actual risks of using $, and if [[ is preferred are there any circumstances where it is appropriate to use $-extraction?

Upvotes: 0

Views: 75

Answers (1)

submartingale
submartingale

Reputation: 755

Consider the list:

foo<-list(BlackCat=1,BlackDog=2, WhiteCat=3,WhiteDog=4)

Suppose you want to call the indice according to the two user parametric variables: colour and animal species. Parametrising the colour and the species somewhere in the code as

myColour<-"Black"
mySpecies<-"Dog"

you can make the call to index parametric easily as

foo[[paste0(myColour,mySpecies)]]

by using [[ or [. However, this is not case for $ extraction: foo$paste0(myColour,mySpecies) would not evaluate the function paste0.

Upvotes: 2

Related Questions