gpt4 book ai didi

r - 为什么 R 函数中拼写不完整的名称可以找到匹配项?

转载 作者:行者123 更新时间:2023-12-04 11:38:14 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why does R use partial matching?

(1 个回答)


8 年前关闭。



f=function(s,abc=0,def=0) {
return(s+def)
}

f(3)
[1] 3
f(3,d=4)
[1] 7

为什么 R 将“d”与“def”匹配?

是否有规则说当在函数中找不到变量的名称时,R 会自动匹配一个与它的大写字母相同的名称?

最佳答案

有三种主要的方法来匹配参数。这些在 Argument Matching 中进行了讨论。 R Language Definition的部分,我在下面复制了相关部分:

The first thing that occurs in a function evaluation is the matching of formal to the actual or supplied arguments. This is done by a three-pass process:

  1. Exact matching on tags. For each named supplied argument the list of formal arguments is searched for an item whose name matches exactly. It is an error to have the same formal argument match several actuals or vice versa.
  2. Partial matching on tags. Each remaining named supplied argument is compared to the remaining formal arguments using partial matching. If the name of the supplied argument matches exactly with the first part of a formal argument then the two arguments are considered to be matched. It is an error to have multiple partial matches. Notice that if f <- function(fumble, fooey) fbody, then f(f = 1, fo = 2) is illegal, even though the 2nd actual argument only matches fooey. f(f = 1, fooey = 2) is legal though since the second argument matches exactly and is removed from consideration for partial matching. If the formal arguments contain ... then partial matching is only applied to arguments that precede it.
  3. Positional matching. Any unmatched formal arguments are bound to unnamed supplied arguments, in order. If there is a ... argument, it will take up the remaining arguments, tagged or not.


请注意,这是正常功能会发生的情况。原始函数在 R 中是特殊的。原始函数在很多方面都很特殊,并且总是不使用标签而是使用位置匹配。然而,这并非始终适用。

另一个重要的异常(exception)是函数中包含 ... 的参数。争论。如上所述,如果参数发生在 ... 之后在函数的参数列表中,您必须在调用该函数时命名该参数 如果 因为位置匹配不适用于这些参数。例如:
foo <- function(x, ..., y) {
y
}

将值传递给 y 的唯一方法是在函数调用中命名,例如:
foo(y = 1)

关于r - 为什么 R 函数中拼写不完整的名称可以找到匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15767036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com