Adding and Editing Functions of R-package

拈花ヽ惹草 提交于 2020-07-31 05:31:11

问题


Goal: I downloaded an R-package "ABC" from CRAN and would like to achieve two things:

  1. edit an existing function ex_fct of that R-package.
  2. 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:

  1. 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).
  2. 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 the ex_fct function as desired and added the nw_fct also to that file (because the ex_fct and nw_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.
  3. Finally, I used the build function of the devtools 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), where path1 navigates to the place of the updated package folder and path2 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).
  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!