Function argument matching: by name vs by position

前端 未结 1 1645
长情又很酷
长情又很酷 2021-01-19 17:00

What is the difference between this lines of code?

mean(some_argument)

mean(x = some_argument)

The output is the same, but has the explici

相关标签:
1条回答
  • 2021-01-19 17:31

    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.

    See also the R Language Definition: 4.3.2 Argument matching

    0 讨论(0)
提交回复
热议问题