我正在尝试将代码插入 Rprofile.site 以允许整数相乘而不溢出。 如果运行此代码,请小心,它会重载 * 运算符。如果运行它,您可以将 oldMult 存储回 [tick][asterisk][tick] 以将其设置回来
当我将其放入 Rprofile 时,如下所示
print("test1")
oldMult<-`*`
`*`<-function(A,B){
if(is.integer(A) || is.integer(B))
{
return(oldMult(as.numeric(A),as.numeric(B)))
} else return (oldMult(A,B))
}
print("test2")
.First <- function()
{
print("test3")
oldMult<-`*`
`*`<-function(A,B){
if(is.integer(A) || is.integer(B))
{
return(oldMult(as.numeric(A),as.numeric(B)))
} else return (oldMult(A,B))
}
print("test4")
#blah blah
}
我收到此错误
Error: cannot change value of locked binding for '*'
“test1”打印,oldMult 显示为
> oldMult
function (e1, e2) .Primitive("*")
但奇怪的是,如果我只运行完全相同的代码
`*`<-function(A,B){
if(is.integer(A) || is.integer(B))
{
return(oldMult(as.numeric(A),as.numeric(B)))
} else return (oldMult(A,B))
}
效果很好
> as.integer(1000000000) * as.integer(1000000000)
[1] 1000000000000000000
有什么不同?这和环境有关系吗?
> environmentIsLocked(.GlobalEnv)
[1] FALSE
> bindingIsLocked(*,.GlobalEnv)
Error: unexpected '*' in "bindingIsLocked(*"
> bindingIsLocked("*",.GlobalEnv)
Error in bindingIsLocked("*", .GlobalEnv) : no binding for "*"
> bindingIsLocked(`*`,.GlobalEnv)
Error in bindingIsLocked(`*`, .GlobalEnv) : not a symbol
最佳答案
> bindingIsLocked("*", env=baseenv())
[1] TRUE
将 bindingIsLocked("*",environment())
放入您要重写的函数之前。然后你会看到它是否被锁定在本地环境中(environment()
)
关于r - 重写 Rprofile.site 中的 * 运算符来处理整数溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528944/