简体   繁体   中英

R source command in package

How can I source my function files in r-packages?

Example (tree dir of my package, package name is "pack"):

- man (help files)
- R
 -- pack.function1.R
 -- pack.function2.R
 -- ...
- myfunctions
 -- functions.R
DESCRIPTION
NAMESPACE
...


functions.R
foo <- function(bar) {
   return(bar)
}


pack.function1.R
...
source("myfunctions/functions.R")
foo(bar)

I tried "myfunctions/functions.R", "/myfunctions/functions.R", "../myfunctions/functions.R" but it does work.

How is the correct source path? It's my first try with R packages.

It looks like you are trying to organize the R code files in your package into different (sub) folders.

This is not supported within R packages.

If you install your package you can query the installation path from a function within your package:

system.file(package = "data.table")
[1] "/home/ryoda/R/x86_64-pc-linux-gnu-library/3.4/data.table"

But if you look into the R folder of the installed package you will not find your R code but a "precompiled" image of all your R code (see the *.rdb and *.rdx files).

Therefore you cannot source other R source code files within R.

For details around the folder structure see: https://cran.r-project.org/doc/manuals/R-exts.html#Data-in-packages

PS: There is (at least) one "back-door":

If you put R files of your package into a sub folder under the package root named inst the contents of the inst sub folder will be copied recursively to the installation directory and could be source then (use system.file(package = getPackageName()) to retrieve the installation path from within your package.

But this is far beyond the way a package should work.

A valid exception could be: Provide pre-configured configuration files that are pure R files creating variables...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM