Simple but supported code reuse

Let's say I have a tiny (3-4 lines) function that I often use.

Since it is so small, it is easy to copy and paste into every source file that it needs, but copy-paste is not a supported form of code reuse.

Instead, I would like to put this function in my own file and somehow import it from other source files as needed.

I have found only two ways to do this so far:

  • create an R package for my function, install it in my R-library and run client code, for example. library(myfunction);
  • execute client code source("path/to/my/function.R").

(The first option seems to me very difficult for a simple use case, which I have in mind. At the moment, I am not going to transfer this function to CRAN or even share it with anyone else. All I want to do is use it from my original R scripts.)

Is there any other way to do this?


In Python, for example, I can put a tiny function in some file:

# hello.py

def hello():
    print "hello, world"

... and put this file in a directory in my variable PYTHONPATH. Then, to use the function in any script some_script.py, all I have to do is

# some_script.py

import hello

hello.hello()
# hello, world

Basically I am looking for the closest equivalent to this in R.

+4
source share
2 answers

You can add it to your own ~/.Rprofileand simply define it there.

: , , if (interactive()) .. . .

: .

+6

, , . , CRAN.

, , . .

.

R

package.skeleton(name = "OneFunc", path = [package_path])

.R [package_path]/R . , , .

my_useful_function <- function(x){
  x^2
}

R

devtools::install_local([package_path])
library(OneFunc)
my_useful_function(3)

9.

, , ( ) , CRAN .

:

  • - , library(OneFunc) . , , , - .
  • , source, ( ).
  • . , , OneFunc, - R .

:

  • . , library, , . , , , /.Rprofile, .

, , , , . , .

+6

Source: https://habr.com/ru/post/1656270/


All Articles