Schleifer Grigorij Schleifer Grigorij - 1 year ago 72
R Question

Matching by name vs matching by position in R

what is the difference between this lines of code?


mean(x = some_argument)

The output is the same, but has the explicit mention of x any advantages?


lmo lmo
Answer Source

People typically don't add argument names for commonly used arguments, such as the x in mean, but almost always refer to the na.rm arguments when removing missing values.

While neglecting the argument name makes for compact code, here are four (related) reasons for including the names of arguments rather than relying on their position.

  1. Re-order arguments as needed. When you refer to the arguments by name, you can arbitrarily re-order the arguments and still produce the desired result. Sometimes it is useful to re-order your arguments. For example, when running a loop over one of the arguments, you might prefer to put the looped argument in the front of the function.
  2. It is typically safer / more future-proof. As an example, if some user-written function or package re-orders the arguments in an update, and you relied on the positions of the arguments, this would break your code. In the best scenario, you would get an error. In the worst scenario the function would run, but would an incorrect result. Including the argument names greatly reduces the chances of running into either case.
  3. For greater code clarity. If an argument is rarely used or you want to be explicit for future readers of your code (including you 2 months from now), adding the names can make for easier reading.
  4. Ability to skip arguments. If you want to only change the third argument, then referring to it by name is probably preferable.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download