为什么在使用显式参数时 R 的 attributes() 函数会失败?

Why does R's attributes() function fail when using explicit arguments?

我正在与 RODBCparallel 合作,针对一些内部报告对数据系统进行多次查询。为了便于建立新连接,我将从 RODBC 对象中提取连接字符串。为此,我计划使用 attributes()。但是,我遇到了一种我不理解的行为。下面是一个最小的工作示例:

> example.data <- data.frame(letters = sample(x = LETTERS,size = 20,replace = T),
+                            numbers = sample(x = 0:9,size = 20,replace = T))
> 
> attributes(obj = example.data)
Error in attributes(obj = example.data) : 
  supplied argument name 'obj' does not match 'x'
> attributes(example.data)
$names
[1] "letters" "numbers"

$row.names
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

$class
[1] "data.frame"

应该注意 obj = 行为是 RStudio 建议的选项卡。但是,它会导致错误。我试图查看 attributes 的源代码,但它是原始代码,所以我必须深入研究 C 源代码——我对它不太熟悉。

为什么使用显式参数 (obj =) 时 attributes() 失败,但不使用时运行正常? (RStudio 关于建议 obj = 的行为是否应该改变?)

这似乎是属性文档中的错误。该参数可能应该命名为 x。你可以这样称呼它

attributes(x = example.data)

问题是 attributes() 是原始函数,原始函数的行为与 R 中的常规函数​​不同。它们没有形式参数 (formals(attributes) returns NULL).对于这些类型的函数,R 通常不会按名称解析参数,并且出于效率原因会假定它们处于特定的位置顺序。这就是为什么最好不要命名它们的原因,因为您无法更改这些参数的顺序。这里应该不需要命名参数。

还有其他函数在文档中的参数名称与代码检查的值之间存在不匹配。例如

isS4(pi)
# [1] FALSE
# documented parameter name is "object"
isS4(object=pi)
# Error in isS4(object = pi) : 
#   supplied argument name 'object' does not match 'x'
isS4(x=pi)
# [1] FALSE

但也有其他原语使用 x 以外的名称:例如seq_along(使用 "along.with=")和 quote(使用 "expr=")。