Opérateur d'extraction R: [vs $ [duplicate]

Sep 28 2020

Il existe plusieurs articles sur Internet concernant les différences et les similitudes entre [et $. Je vois un article où il $est recommandé uniquement pour une utilisation interactive mais pas pour la programmation. Cependant, je ne suis pas sûr de comprendre si c'est une préférence ou s'il y a une explication derrière cette idée.

Disons maintenant que j'écris un package ou une fonction, si j'extrais un élément par son nom (par exemple, mtcars[["mpg"]]) pourquoi devrais-je éviter d'utiliser mtcars$mpg?

Réponses

5 GregorThomas Sep 28 2020 at 17:42

There are two differences that really matter between [[ and $:

  1. [[ - works with strings (i.e. it supports variable substitution), $ doesn't. If you have my_var = "mpg", you can use mtcars[[my_var]], but there isn't a good way to use my_var with $.

  2. $ auto-completes, if a partial column name is unambiguous. mtcars$m will return the mpg column, mtcars[["m"]] will return NULL. mtcars$d will return NULL because multiple columns start with a "d".

#1 makes [[ more flexible for programming - it's extremely common in programmatic use to be working with column names stored as strings.

#2 makes $ more dangerous - you should not use abbreviated column names in programming, however in interactive use it can be nice and quick. (Though this is largely moot with RStudio's auto-completion features, if you use that IDE.)

2 StéphaneLaurent Sep 28 2020 at 17:40

$ does partial matching: if you have a column named xxx in a dataframe dat, then dat$xx will return the xxx column (unless you also have a xx column). This can be dangerous.

I always use [["..."]] for another reason: I use RStudio, and there is a nice highlighting for strings, whereas there's no highlighting with $.