如何修改模块中库的函数 [英] How to modify a function of a library in a module

查看:48
本文介绍了如何修改模块中库的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题 - 在这样开头的脚本中:

I have the following problem - in a script starting like that:

modules::import("modules")
modules::import("futile.logger")
modules::import("data.table")
modules::import("REDCapR")

用作在其他脚本中使用 modules::use 的模块,我想使用 REDCapR 包的 redcap_write 函数的修改版本.

used as a module using modules::use in an other script, I would like to use a modified version of the function redcap_write of the package REDCapR.

我不知道如何继续.在我看来,有两种可能:

I don't know how to proceed. To my point of view there are two possibilities:

  • 使用本地存储的 redcap_write 的修改版本.那会很棒,因为它很容易分享.但是我不知道如何强制R用我本地的修改版本替换包的redcap_write函数.modules::use 只会导入修改后的函数,但不会替换 redcap_write

  • Use a modified version of redcap_write stored locally. That would be great, because it would be an easy mofication to share. But I don't know how to force R to replace the redcap_write function of the package by my local modified version. modules::use would only import the modified function but would not replace the package version of redcap_write

安装我在此处创建的 REDCapR 包的分叉版本 https://github.com/dmongin/REDCapR/tree/overwrite.但是我不知道如何以简单的方式进行(卸载 REDCapR 来安装我的分叉版本会有点繁琐:我们在不同的开发人员/用户之间共享代码,每个人都应该卸载并重新安装包)

Install a forked version of REDCapR package, that I created here https://github.com/dmongin/REDCapR/tree/overwrite. But I don't know how to do in a simple manner (uninstalling REDCapR to install my forked version would be a bit tidious: we share the code between various developper/users, each should uninstall and reinstall the package)

推荐答案

您将不得不修改包命名空间下的内容.这是一个将 redcap_write() 替换为 mean() 函数的示例.

You would have to modify the things under the package Namespace. Here is one example replacing redcap_write() with the mean() function.

ns <- asNamespace("REDCapR")
fn <- "redcap_write"

unlockBinding(fn, ns)
ns[[fn]] <- mean
lockBinding(fn, ns)

检查它是否有效:

library(REDCapR)

> redcap_write
function (x, ...)
UseMethod("mean")
<bytecode: 0x7f8120229100>
<environment: namespace:base>

> REDCapR::redcap_write
function (x, ...)
UseMethod("mean")
<bytecode: 0x7f8120229100>
<environment: namespace:base>

为了redcap_write在其体内调用适当的函数,你必须在REDCapR环境中设置它.这应该可以工作(假设 newversion 是您更正的 redcap_write 函数):

In order to redcap_write to call the proper functions inside its body, you have to set it in the REDCapR environment. This should work (assuming newversion is your corrected redcap_write function):

ns <- asNamespace("REDCapR")
fn <- "redcap_write"
unlockBinding(fn, ns)
environment(newversion) <- ns
ns[[fn]] <- newversion
lockBinding(fn, ns)

这篇关于如何修改模块中库的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆