在R中更改函数和解锁绑定
我面临的问题是更改在R中更改函数和解锁绑定,r,function,binding,R,Function,Binding,我面临的问题是更改箱线图函数,以便胡须延伸到5和95分位数。我知道我不是第一个尝试这个的人 我读过这些帖子 并在下面编写了注释代码,该代码应将boxplot.default代码更改为使用“myboxplot.stats”而不是“boxplot.stats”,但它不起作用。当我运行fixInNamespace时,我得到一个错误,我无法更改boxplot.default,因为它被锁定了。由于我以前从未使用过名称空间、环境和bildings,代码中可能存在明显的错误。如果是这样的话,我很
箱线图
函数,以便胡须延伸到5和95分位数。我知道我不是第一个尝试这个的人
我读过这些帖子
boxplot.default
代码更改为使用“myboxplot.stats”而不是“boxplot.stats”,但它不起作用。当我运行fixInNamespace
时,我得到一个错误,我无法更改boxplot.default,因为它被锁定了。由于我以前从未使用过名称空间、环境和bildings,代码中可能存在明显的错误。如果是这样的话,我很高兴,如果你能把它也指给我看,或者给我一些建议如何正确地做这件事
我很感激
### new boxplot stats function with 5%/95% whiskers
### source: https://stat.ethz.ch/pipermail/r-help/2001-November/016817.html
myboxplot.stats <- function (x, coef = NULL, do.conf = TRUE, do.out = TRUE) {
nna <- !is.na(x)
n <- sum(nna)
stats <- quantile(x, c(.05,.25,.5,.75,.95), na.rm = TRUE)
iqr <- diff(stats[c(2, 4)])
out <- x < stats[1] | x > stats[5]
conf <- if (do.conf)
stats[3] + c(-1.58, 1.58) * diff(stats[c(2, 4)])/sqrt(n)
list(stats = stats, n = n, conf = conf, out = x[out & nna])
}
old.boxplot <- boxplot.default ### for comparison
### https://stackoverflow.com/questions/23279904/modifying-an-r-package-function-for-current-r-session-assigninnamespace-not-beh
fixInNamespace("boxplot.default", ns = "graphics")
### Error in assignInNamespace(subx, x, ns) :
### locked binding of ‘boxplot.default’ cannot be changed
### how to unlock binding:
### https://stackoverflow.com/questions/19132492/how-to-unlock-environment-in-r
### http://adv-r.had.co.nz/Environments.html
### in boxplot.default I find: '<environment: namespace:graphics>'
unlockBinding(sym = "boxplot.default", env = asNamespace("graphics"))
### checking if it worked (https://gist.github.com/wch/3280369#file-unlockenvironment-r)
bindingIsLocked(sym = "boxplot.default", env = asNamespace("graphics")) ### FLASE
fixInNamespace("boxplot.default", ns = "graphics") ### here I want to change 'boxplot.stats' to 'myboxplot.stats'
### Error in assignInNamespace(subx, x, ns) :
### locked binding of ‘boxplot.default’ cannot be changed
lockBinding(sym = "boxplot.default", env = asNamespace("graphics"))
new.boxplot <- boxplot.default ### for comparison
###具有5%/95%胡须的新箱线图统计功能
###资料来源:https://stat.ethz.ch/pipermail/r-help/2001-November/016817.html
myboxplot.stats如果需要,可以使用Github的godmode
包:
# save original version
orig <- graphics::boxplot.default
# devtools::install_github("miraisolutions/godmode")
godmode:::assignAnywhere("boxplot.default", boxplot.default_new)
# switch back
godmode:::assignAnywhere("boxplot.default", orig)
#保存原始版本
orig谢谢RolandASc,我测试了你的代码,对初学者来说很容易理解,而且很有效!我是否正确地假设,使用名为godmode
的包和您提供的替换现有函数的结构,我可以根据自己的需要在其名称空间/环境/位置中更改任何函数?好吧,这会让您走得很远,但它不能涵盖所有可能的情况。因此,与其说是任何
,不如说是许多
:)不用说,最好将这种替换保持在最低限度