开发者

Embed fix() function within .R script?

开发者 https://www.devze.com 2023-01-22 12:17 出处:网络
I am looking for a way to embed the fix() function within a script. Basically, here\'s what I\'m currently doing:

I am looking for a way to embed the fix() function within a script. Basically, here's what I'm currently doing:

  1. I load a certain package. For example, library(PerformanceAnalytics)
  2. I call the fix() function to edit a couple functions within the loaded package. Example, fix(VaR).
  3. Then, using R's bu开发者_开发问答ilt-in editor, I copy-paste my function over the one originally loaded from the package.
  4. Finally, I source in my .R script which calls the above functions I fixed and performs the computations I need.

Essentially, I'd like to streamline Step 3 above. Rather than having to manually type fix(function) and copy-paste over the original functions within the loaded package, I'd rather just have it done within a script I source.

Is there anyway to accomplish this?

FYI, I have reached out to the package's creator and loading a re-compiled version of the package with my modified code is out of the question.


Maybe source your functions and then use assignInNamespace?


EDIT #1:
The above won't work because assignInNamespace doesn't alter objects that have been exported. Instead,

  1. put your functions in a file (foo.R)
  2. load the package
  3. then source(foo.R) or sys.source(foo.R, envir=attach(NULL, name="myenv"))

Your functions will be higher up on the search list if you load them after the package, so R will find them before getting to the package's functions with the same name.


EDIT #2:
I didn't realize VaR called unexported functions in the namespace. That's why EDIT #1 doesn't work. To get it to work, you would need to explicitly reference all unexported PerformanceAnalytics functions used in VaR (e.g. change VaR.Gaussian to PerformanceAnalytics:::VaR.Gaussian).

See this post on R-devel for a couple other approaches. I couldn't quickly get Prof. Ripley's solution to work (I get the same error as in EDIT #1) and I didn't try Gabor's solution.


You can edit the body directly, discussed here:

What ways are there to edit a function in R?


You can download the packages source from CRAN. Edit the function (it will be found in PackageName/R), then install this package into R and just use it that way.

You can even change the package name in the DESCRIPTION file ... call it "PerformanceAnalytics2", then in R you just library(PerformanceAnalytics2) and use it as you would the original package.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号