Opérateur d'extraction R: [vs $ [duplicate]
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
There are two differences that really matter between [[ and $:
[[- works with strings (i.e. it supports variable substitution),$doesn't. If you havemy_var = "mpg", you can usemtcars[[my_var]], but there isn't a good way to usemy_varwith$.$auto-completes, if a partial column name is unambiguous.mtcars$mwill return thempgcolumn,mtcars[["m"]]will returnNULL.mtcars$dwill returnNULLbecause 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.)
$ 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 $.