【问题标题】:changing functions and unlocking bindings in R在 R 中更改功能和解锁绑定
【发布时间】:2018-03-02 15:12:21
【问题描述】:

我面临更改boxplot 函数以使晶须延伸到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

【问题讨论】:

    标签: r function binding


    【解决方案1】:

    如果需要,可以使用 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)
    

    boxplot.default_new 应该是你对boxplot.default 的重写,可能包括你的函数myboxplot.stats(甚至可能重命名)和对它的调用。

    【讨论】:

    • 谢谢 RolandASc,我测试了你的代码,对于初学者来说很容易理解,并且成功了!我是否正确地假设,使用名为 godmode 的包和替换现有函数的结构,我可以在它们的命名空间/环境/位置中根据需要更改任何函数?
    • 好吧,这将带您走很远,但它不能涵盖所有可能的情况。因此,我们只说many 而不是any :) 不用说最好将此类替换保持在最低限度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多