You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中附加中缀运算符后UseMethod无法匹配方法的问题

附加对象的优势(可跳过)

在脚本中可以通过以下方式便捷定义辅助函数,既能正常使用函数,又不会污染全局环境:

f <- function() print('hi')
e <- new.env()
assign("f", f, e)
rm(f)
attach(e)
rm(e)

此时f处于受保护状态,全局环境中不会出现该对象:

ls()
#> character(0)  # 无"f"对象
rm(f)
#> In rm(f) : object 'f' not found

但存储f的环境e仍在R的搜索路径内:

search()
#> [1] ".GlobalEnv" "e" ... etc 

因此依然可以正常调用f:

f()  
#> [1] "hi"

若在全局环境重新定义一个f,调用时会优先使用全局环境的版本,但附加环境中的f不会被删除:

f <- function() print('hello')
f()  
#> [1] "hello"
rm(f)
f()  
#> [1] "hi" # 再次调用附加环境中的函数

如果要彻底移除这个附加的f,需要将它所在的环境从搜索路径中移除:

detach(e)
f()
#> Error in f() : could not find function "f"

附加运算符

创建简单中缀运算符

可以定义如下中缀运算符,通过方法分派实现不同类型的运算逻辑:

`%plus%` <- function(x,y) UseMethod("%plus%")
`%plus%.numeric` <- function(x, y) x + y
1 %plus% 1
#> 2

这只是简化示例,实际可基于该思路定义更复杂的%+%类运算符。

问题现象

尝试将%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%") : 
  没有适用于'%plus%'的方法可应用于类为"c('double', 'numeric')"的对象

但查看运算符时,两个函数均可见:

`%plus%`
#> function(x,y) UseMethod("%plus%")
#> <bytecode: 0x557b338c86c0>

`%plus%.numeric`
#> function(x, y) x + y

且直接以函数形式调用方法时,运行完全正常:

`%plus%.numeric`(1, 1)
#> 2

内容的提问来源于stack exchange,提问作者antonio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 06:45:18