DFA
DFA

Reputation: 11

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. To do this I extracted the function code, modified it, and saved it as an .R file, which I then source to use. 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:

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.

Upvotes: 1

Views: 60

Answers (1)

MrFlick
MrFlick

Reputation: 206197

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

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

Upvotes: 2

Related Questions