本文介绍了函数参数匹配:按名称与按位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这几行代码有什么区别?

What is the difference between this lines of code?

mean(some_argument)

mean(x = some_argument)

输出是一样的,但是明确提到了 x 有什么好处吗?

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

推荐答案

人们通常不会为常用参数添加参数名称,例如 mean 中的 x,但几乎总是引用na.rm 删除缺失值时的参数.

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. 根据需要重新排列参数.当您按名称引用参数时,您可以任意重新排列参数并仍然产生所需的结果.有时重新排列参数很有用.例如,当对其中一个参数运行循环时,您可能更愿意将循环参数放在函数的前面.
  2. 这通常更安全/更具前瞻性.例如,如果某些用户编写的函数或包在更新中重新排序参数,而您依赖于参数的位置,这会破坏您的代码.在最好的情况下,你会得到一个错误.在最坏的情况下,该函数会运行,但会产生不正确的结果.包含参数名称会大大减少遇到任何一种情况的机会.
  3. 为了使代码更加清晰.如果某个参数很少使用,或者您希望对代码的未来读者(包括从现在起 2 个月后的您)明确,添加名称可以使阅读更容易.
  4. 能够跳过参数.如果您只想更改第三个参数,那么按名称引用它可能更可取.
  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.

另见 R 语言定义:4.3.2 参数匹配

这篇关于函数参数匹配:按名称与按位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:15