Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple yet maintainable code re-use

Tags:

r

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

Since it's so small, it's easy to copy-paste it into every source file that needs it, but copy-paste is not a maintainable form of code re-use.

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

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

  1. create an R package for my function, install it in my R library, and have client code run, e.g. library(myfunction);
  2. have client code execute source("path/to/my/function.R").

(The first option strikes me as very heavy-handed for the simple use-case I have in mind. At the moment, I don't intend to submit this function to CRAN, or even to share it with anyone else. All I want to do is use it from my throwaway R scripts.)

Is there some other way to do this?


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

# hello.py

def hello():
    print "hello, world"

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

# some_script.py

import hello

hello.hello()
# hello, world

I'm basically looking for the closest equivalent to this in R.

like image 304
kjo Avatar asked Dec 15 '22 03:12

kjo


1 Answers

You can add it to your ~/.Rprofile and just define it there.

Plus: One location, always sourced, can even control via if (interactive()) etc pp. Less work than a package.

Minus: Global visibility.

like image 131
Dirk Eddelbuettel Avatar answered Jan 02 '23 09:01

Dirk Eddelbuettel