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:
library(myfunction)
;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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With