愚弄R的方法调度

问题描述 投票:0回答:1

我正在寻找一个示例,其中函数名称中的点导致 R 的 Method Dispatch 选择错误的函数。一个自然的候选者似乎是内置函数

t.test()
,当应用于“test”类的对象时,应该与
t()
混淆。

然而奇怪的是,下面的代码实际上调用的是转置函数而不是

t.test()
:

> x <- structure(cbind(1:4,2:5), class="test")
> class(x)
[1] "test"
> t(x)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    3    4    5

这提出了两个问题:

  1. 为什么对象被转置而不是
    t.test()
    被调用,这应该是由于方法调度的规则造成的?
  2. 通过定义内部带有点的函数来搞乱方法调度过程的(简单)示例是什么?
r overloading
1个回答
0
投票

您还必须考虑评估函数的环境。例如,如果您在

stats
环境中运行此命令,您将得到

t(x)
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]    2    3    4    5
# attr(,"class")
# [1] "test"

evalq(t(x), envir=asNamespace("stats"))
#   One Sample t-test
# 
# data:  x
# t = 6.4807, df = 7, p-value = 0.0003402
# alternative hypothesis: true mean is not equal to 0
# 95 percent confidence interval:
#  1.905392 4.094608
# sample estimates:
# mean of x 
#         3 

所以问题是

t()
函数定义在
base
命名空间中,而
t.test()
位于
stats
中。默认情况下首先找到转置。

© www.soinside.com 2019 - 2024. All rights reserved.