gpt4 book ai didi

function - 覆盖命名空间中导入的函数

转载 作者:行者123 更新时间:2023-12-02 14:32:45 25 4
gpt4 key购买 nike

由于 R 中的 termplot 函数包含一些奇怪的代码,这些代码给我带来了烦人的错误,我想在我自己的测试代码中覆盖它,直到找到更永久的解决方案。问题是 mgcv 包未加载更改的函数。 mgcv 包使用 NAMESPACE 文件中的 importFrom() 从其命名空间中的 stats 包加载 termplot。

如何说服 mgcv 使用更改后的 termplot?我尝试过:

unlockBinding("termplot", as.environment("package:stats"))
assign("termplot", my.termplot, as.environment("package:stats"))
lockBinding("termplot", as.environment("package:stats"))

当应用于 lm-objects 时,此方法有效并且使用更改后的 termplot。但是当使用 mgcv 包制作的 gam-objects 时,这不起作用。如果我可以避免的话,我真的不会从源代码构建统计数据包......

为了澄清,我也尝试过

assignInNamespace("termplot", my.termplot, ns="stats")
assignInNamespace("termplot", my.termplot, ns="mgcv")

在所有可能的组合中,在附加 mgcv 之前、附加 mgcv 之后,我都没有设法让它工作。

<小时/>

编辑:

我尝试了此处给出的所有选项(除了重建任一包),但无法使其工作。对我来说最简单的方法是使用包装函数。该讨论可以找到 here 。感谢您提供的所有提示。

<小时/>

可重现的示例:

my.termplot <- function (x) print("my new termplot")

unlockBinding("termplot", as.environment("package:stats"))
assignInNamespace("termplot", my.termplot, ns="stats", envir=as.environment("package:stats"))
assign("termplot", my.termplot, as.environment("package:stats"))
lockBinding("termplot", as.environment("package:stats"))


y <- 1:10
x <- 1:10
xx <- lm(y~x)
termplot(xx)
require(mgcv)
dat <- gamSim(1, n = 400, dist = "normal", scale = 2)
b <- gam(y ~ s(x0) + s(x1) + s(x2) + x3, data = dat)
plot(b,all=TRUE)

plot.gam 为非平滑项(本例中为 x3)调用 termplot,但无法找到新的 termplot 函数。

<小时/>

EDIT2:显然,我的示例有效。我现在看到我解决了我自己的问题:在第一个代码中,我没有在 allocateInNamespace 中添加命名空间和包。重要的是要记住在加载其他包之前更改命名空间和包中的函数。感谢@hadley 为我指明了正确的方向,感谢@Marek 测试了代码并报告其工作原理,感谢其余的人努力回答。

最佳答案

我很困惑 - 我无法弄清楚 plot.gam 如何定位 termplot - 据我所知,它没有使用普通的范围规则。这似乎需要比我目前对命名空间有更深入的了解。

my.termplot <- function (x) print("my new termplot")

# where is it defined?
getAnywhere("termplot")
# in package and in namespace

unlockBinding("termplot", as.environment("package:stats"))
assign("termplot", my.termplot, "package:stats")

unlockBinding("termplot", getNamespace("stats"))
assign("termplot", my.termplot, getNamespace("stats"))

getAnywhere("termplot")[1]
getAnywhere("termplot")[2]
# now changed in both places

y <- 1:10
x <- 1:10 + runif(10)
xx <- lm(y ~ x)
termplot(xx) # works

library("mgcv")
b <- gam(y ~ s(x), data = data.frame(x, y))
plot(b) # still calls the old termplot

# I'm mystified - if try and find termplot as
# seen from the environment of plot.gam, it looks
# like what we want
get("termplot", environment(plot.gam))

关于function - 覆盖命名空间中导入的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6254744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com