问题
Goal: I downloaded an R-package "ABC" from CRAN and would like to achieve two things:
- edit an existing function
ex_fct
of that R-package. - add a new function
nw_fct
to that R-package.
and these adjustments shall be permanent.
Situation: There are good sources that explain the first aspect on how to edit/change/overwrite an existing function of an R-package here, but trying to follow this approach seems not to work for adding new functions to a package.
Question: Hence, I wish to add the function nw_fct
as a hidden function in that package so that it can be called via ABC:::nw_fct
. How can this be done? Is there a way to simultaneously address both aspects?
回答1:
Solution: The following steps worked for me (on a Mac) to simultaneously solve both aspects:
- I downloaded package ABC as a tar file from the CRAN repository (file: "ABC_1.1-2.tar"). After opening the file by decompressing it via double-click, it shows the typical structure of Packages (metadata, vignettes, namespace, etc.) as described in the link provided by alistaire (see here - very helpful, many thanks).
- All the relevant files with the different algorithms (e.g. files "algo-A.R", "algo-B.R") are contained in the "R"-folder and inside the file "algo-A.R", I found the function
ex_fct
. I opened this file in R-Studio adjusted theex_fct
function as desired and added thenw_fct
also to that file (because theex_fct
andnw_fct
functions are related) and saved it under the same name, i.e. as "algo-A.R". As a result, I now have an updated package folder that contains my updated version of the "algo-A.R" file. - Finally, I used the
build
function of thedevtools
package to create a single bundled ".tar" file (say file "ABC_new.tar") from this updated package folder. Specifically, one may simply use:build(pkg= "path1/ABC_1.1-2", path= "~path2/ABC_new.tar", manual=F, binary=F)
, wherepath1
navigates to the place of the updated package folder andpath2
says where the bundled package shall be stored. Notice: As I did this on a new machine, this step did not work immediately but required to first install e.g. TeXLive, Java Applications as well as several packages required by the ABC package (simply follow R's error commands). - Finally, I was able to (permanently) install the updated package archive file in RStudio via:
install.packages(“~path2/ABC_new.tar", repos = NULL, type=“source”)
Should you wish to undo these changes and have the original package again, you may simply remove the package and re-install the original one from CRAN.
来源:https://stackoverflow.com/questions/62852176/adding-and-editing-functions-of-r-package