函数参数匹配:按名称对按位置 [英] Function argument matching: by name vs by position

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

问题描述

这两行代码有什么区别?

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. 为了使代码更清晰.如果很少使用自变量,或者您想对以后的代码读者(包括从现在开始的两个月)明确显示自变量,则添加名称可以使阅读更容易
  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参数匹配

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆