简体   繁体   English

如何在R的新功能中使来自不同环境的对象可用?

[英]How can you make objects from different environments available in new functions in R?

I need to modify one function from an R package to accommodate my analysis needs. 我需要从R包中修改一个函数来满足我的分析需求。 To do this I extracted the function code, modified it, and saved it as an .R file, which I then source to use. 为此,我提取了功能代码,对其进行了修改,然后将其保存为.R文件,然后将其用作源文件。 Yet, because this function uses nested functions from the original R package, it gave me an error even when I load the original library from within the modified function: 但是,因为此函数使用原始R包中的嵌套函数,所以即使从修改后的函数中加载原始库,它也会给我一个错误:

Error in CS.prepMOD(n.POPS = length(sample.locales), response = gen.data[lower.tri(gen.data)],  
: could not find function "To.From.ID"

I could potentially solve this by specifying where to look for each nested function. 我可以通过指定在哪里查找每个嵌套函数来解决此问题。 For example: 例如:

get('To.From.ID',envir=getNamespace('ResistanceGA'))

However, doing this for every single nested function is too cumbersome. 但是,对每个嵌套函数执行此操作太麻烦了。 Instead I tried to source my modified function into the original package environment, but I also got an error: 取而代之的是,我尝试将修改后的函数提供给原始包环境,但是我也遇到了一个错误:

source('newCS_prep.R',local=getNamespace('ResistanceGA'))
Error in eval(expr, envir, enclos) : 
cannot add bindings to a locked environment

So, my question is, is there an way to pass all objects from the original package into my modified function? 所以,我的问题是,有没有办法将所有对象从原始包传递到我的修改函数中?

Thanks in advance for your help. 在此先感谢您的帮助。

You can set the environment of your replacement function to the namespace of the package. 您可以将替换函数的环境设置为包的名称空间。 That way the "internal" function should resolve to those that already exist in the original package. 这样,“内部”功能应解析为原始程序包中已经存在的功能。

Assuming CS.prepMOD is your replacement function, Try 假设CS.prepMOD是您的替换功能,请尝试

environment( CS.prepMOD ) <- getNamespace("ResistanceGA")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在R中制作多维函数数组? - How can you make a multi-dimensional array of functions in R? 您可以在 R6 对象中使用辅助函数吗? - Can you use helper functions inside R6 objects? 如何在 R 中使用重复将不同的数学函数应用于相同的初始变量? 从中创建一个新的向量? - How can I use repeat in R to apply different mathematical functions to the same initial variable? Creating a new vector from this? R函数和Rcpp中的环境 - Environments in R functions and Rcpp 您何时想在R中设置新环境? - when do you want to set up new environments in R 如何从 R 中的列进行新观察? - How can I make new observations from columns in R? 您如何使用从R中的其他数据集创建的模型来预测新数据集的结果? - How do you predict outcomes from a new dataset using a model created from a different dataset in R? 如何在 r 中基于另一个以日期为条件的 df 创建新的 df? - How can you make a new df based on another df with date as condition in r? 如何使用 R 中的 purrr::map 函数从多个 tidymodels 对象中提取 model 摘要? - How can I extract model summary from multiple tidymodels objects using purrr::map functions in R? 从函数返回对象(R) - Returning objects from functions (R)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM