我正在寻找一个示例,其中函数名称中的点导致 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
这提出了两个问题:
t.test()
被调用,这应该是由于方法调度的规则造成的?您还必须考虑评估函数的环境。例如,如果您在
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
中。默认情况下首先找到转置。