- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在这里遇到了一个奇怪的问题:
https://stackoverflow.com/a/11084038/636656
似乎分配给与基函数相同的名称仍然允许您使用基函数:
> print <- FALSE
> print
[1] FALSE
> print("hi")
[1] "hi"
>
> sum <- FALSE
> sum(1:10)
[1] 55
> sum
[1] FALSE
相比之下,将函数分配给与基函数同名的函数不会产生相同的行为:
> sum <- function(x) x^2
> sum(1:10)
[1] 1 4 9 16 25 36 49 64 81 100
> sum
function(x) x^2
我知道它们位于不同的命名空间中,但我对两件事感到好奇:
为什么:这是避免难以恢复的行为(例如,如果您覆盖 rm
)的故障保护吗?预测这种行为的原理是什么?
如何:是否有不同的命名空间函数和逻辑查找例程?
最佳答案
评估对 print()
的调用时, R 搜索(沿其普通搜索路径)名称为 print
的函数 .您的对象print <- TRUE
具有正确的名称,但不是函数,因此搜索会直接跳到第一个具有正确名称的函数。
这是 John Chambers 的解释,来自 Software for Data Analysis: Programming with R 的“第 13 章:R 的工作原理” .
The evaluation of the function call begins by looking for a function corresponding to the name. The rules for "looking for" are the same as the general rules for evaluating names mentioned above, except that the evaluator silently ignores any object found that is not a function, allowing local non-function objects with the same name as non-local functions, a concession motivated by people's tendency to assign objects names such as "c".
(我特别喜欢最后一点,这是“出于人们倾向于……而做出的让步”;)
既然您对此感兴趣,那么也值得一看 match.fun()
,旨在“提取所需的功能对象,同时避免与其他类型的对象进行不需要的匹配”。它包括以下行,很好地说明了评估者和评估者使用的策略:
FUN <- get(as.character(FUN), mode = "function", envir = envir)
关于r - 为什么这行得通?创建与基函数同名的逻辑函数仍然允许使用该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084136/
我是一名优秀的程序员,十分优秀!