简体   繁体   中英

R's equivalent to Python's importing mechanism

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.

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.

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