0

In Python, suppose we have:

lib.py:
def myFunction():
  ...

main.py:
  import lib
  lib.myFunction()

so that myFunction is in module lib and is not going to pollute the global environment.

However, in R, to use myFunction:

lib.R:
myFunction <- function(...) {...}

main.R:
source("lib.R")
myFunction()

so that myFunction is in the global environment. If lib.R has other functions, all of them will be poured into the global environment, which is highly undesirable.

My question is: Is there a way in R to "import" a user-defined function in other files without polluting the global environment?

I guess writing a R package might alleviate the problem, but in my case, it is not worth it to write a full-fledged package.

wdg
  • 1,687
  • 5
  • 17
  • 29
  • You can use `sys.source()` to load functions into an environment other than the global one, but they won't be very fun to execute. You're better off writing a package. Not sure what makes you think it's not worth it if that's exactly the behavior you are after. – MrFlick May 27 '16 at 04:00
  • I've never used it, but you could maybe look at the modules packages by @klmr – joran May 27 '16 at 04:03
  • 2
    See here for a discussion about it: http://stackoverflow.com/q/15789036/324364 – joran May 27 '16 at 04:05
  • Two options: assign to a specific environment or make a package. – IRTFM May 27 '16 at 04:28

1 Answers1

0

If you import two libraries with same function name, you can use libraryname::function(...).

This won't solve your problem, but will ensure you're using the correct function from the correct library.

Jon
  • 2,373
  • 1
  • 26
  • 34