r - 重写 Rprofile.site 中的 * 运算符来处理整数溢出

标签 r

我正在尝试将代码插入 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/

相关文章:

r - 数据框列的 apply 和 sapply 之间的区别?

r - 如何在数据帧上按行应用函数以在 r 中生成新的或扩展的数据帧

R 没有获取用户库

r - 从 R 中每个组第一次越过阈值的列中获取值

r - R中与加载gsl软件包有关的错误

r - R中更改变量名称的函数

R、Windows 和外语字符

r - 使用小时更改 bin 大小 :Minute In ggplot histogram

r - if(ncol.matrix < rep) { : argument is of length zero 中的错误

r - 如何在 R 中为不同的 spplots 使用相同的颜色间隔