gpt4 book ai didi

r - 使用另一个包中的函数而不附加到搜索路径?

转载 作者:行者123 更新时间:2023-12-02 08:50:35 25 4
gpt4 key购买 nike

我用pkgs::function 表示法来访问另一个包中的函数。这有时会导致类似 survival 包中的问题:

data(logan,package="survival")
resp <- levels(logan$occupation)
n <- nrow(logan)
indx <- rep(1:n, length(resp))
logan2 <- data.frame(logan[indx,],
id = indx,
tocc = factor(rep(resp, each=n)))
logan2$case <- (logan2$occupation == logan2$tocc)
survival::clogit(case ~ tocc + tocc:education + survival::strata(id), logan2)

它给出错误:eval(expr, envir, enclos) 中的错误:找不到函数“coxph”

coxph 是另一个从 clogit 函数内部调用的函数。这种情况可以避免吗?我不想将包附加到搜索路径,即按照 Hadley 的 advanced r 最佳实践使用 library(survival)

最佳答案

(放大@RichScriven上面的评论。)

我不完全确定在Advanced R中,您在哪里得到了“不要使用library()”作为最佳实践。也许在 Functions section (请编辑您的问题以澄清我是否有错误!)它说:

The functions that are the easiest to understand and reason about are pure functions: functions that always map the same input to the same output and have no other impact on the workspace. In other words, pure functions have no side effects: they don't affect the state of the world in any way apart from the value they return.

... [points out that library() is an impure function because it changes the search path] ...

It's generally a good idea to minimise the use of side effects, and where possible, to minimise the footprint of side effects by separating pure from impure functions.

请注意此处宽松的措辞:“通常最好尽量减少...在可能的情况下,尽量减少...”这并不意味着“永远不要使用library()”...这是有道理的,你不想把 library() 在函数内,或在包内。如果您使用的是软件包,则可以(应该?)使用 @importFrom survival clogit coxph相反......我发现把 @importFrom我的每个函数开头的标签都可以很好地标记其中使用的外部函数,而我不一定需要 ::识别外部函数(您的情况可能会有所不同)。

但是,如果您实际上是在编写代码来进行生存分析,那么就竭尽全力来避免 library(survival)似乎没有必要。

放大@PierreLafortune上面的评论:clogit内部包含代码 coxcall[[1]] <- as.name("coxph") 。如果将此行更改为 coxcall[[1]] <- as.name("survival::coxph"),您的代码可能会按原样工作。 。您可以发布 issue request on Github about this如果你感觉足够强烈......

关于r - 使用另一个包中的函数而不附加到搜索路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41048850/

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