Override a function that is imported in a namespace

前端 未结 3 1495
梦谈多话
梦谈多话 2020-11-29 04:46

As the termplot function in R is containing some weird code that is giving me annoying bugs, I want to override it in my own test code until I find a more perma

3条回答
  •  感情败类
    2020-11-29 05:13

    Try overwriting the function that you are calling termplot from. At a guess, this is plot.gam in the mgcv package.

    First load the necessary package.

    library(mgcv)
    

    Here's your alternate termplot function, added to the stats namespace.

    my.termplot <- function (model, ...) 
    {
      message("In my.termplot")
    }
    
    unlockBinding("termplot", as.environment("package:stats"))
    assign("termplot", my.termplot, as.environment("package:stats"))
    lockBinding("termplot", as.environment("package:stats"))
    

    Likewise, here's the wrapper function, added to the mgcv namespace.

    my.plot.gam <- function (x, ...) 
    {
      message("In my.plot.gam")
      my.termplot()
    }
    
    unlockBinding("plot.gam", as.environment("package:mgcv"))
    assign("plot.gam", my.plot.gam, as.environment("package:mgcv"))
    lockBinding("plot.gam", as.environment("package:mgcv"))
    

    Here's an example to test it, taken from ?gam.

    dat <- gamSim(1, n = 400, dist = "normal", scale = 2)
    b <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat)
    plot(b) 
    

提交回复
热议问题