Benefit of attaching objects (you can skip this)
在源代码脚本中,可以很方便地定义我们的助手函数,如下所示:
f <- function() print('hi')
e <- new.env()
assign("f", f, e)
rm(f)
attach(e)
rm(e)
现在,f
是某种程度上的保护.它不会扰乱您的全球环境:
ls()
#> character(0) # if anything, no "f"
rm(f)
#> In rm(f) : object 'f' not found
但仍有e
人在搜索路径上:
search()
#> [1] ".GlobalEnv" "e" ... etc
就这样.
f()
#> [1] "hi"
此外,如果我们在全局环境中定义另一个f
,则它优先,但附加的函数受到保护,不会被删除:
f <- function() print('hello')
f()
#> [1] "hello"
rm(f)
f()
#> [1] "hi" # again
要实际移除f
,请移除(分离)其容器:
detach(e)
f()
#> Error in f() : could not find function "f"
Attaching operators
创建平凡的中缀运算符
请考虑以下运算符定义:
`%plus%` <- function(x,y) UseMethod("%plus%")
`%plus%.numeric` <- function(x, y) x + y
1 %plus% 1
#> 2
当然,这是为了简单起见,但人们可以通过复杂的数学来定义一个复杂的%+%
.
这一问题
让我们try 连接我们的%plus%
操作员:
e <- new.env()
assign("%plus%.numeric", `%plus%.numeric`, e)
assign("%plus%", `%plus%`, e)
rm(`%plus%.numeric`)
rm(`%plus%`)
attach(e)
1 %plus% 1
提供:
Error in UseMethod("%plus%") :
no applicable method for '%plus%' applied to an object of class "c('double', 'numeric')"
有趣的是,操作员是可见的:
`%plus%`
#> function(x,y) UseMethod("%plus%")
#> <bytecode: 0x557b338c86c0>
`%plus%.numeric`
#> function(x, y) x + y
使用函数形式而不是中缀形式确实有效:
`%plus%.numeric`(1, 1)
#> 2