简体   繁体   中英

Source .R file as an R package

say I have a file utils.R than contains some functions foo, moo

I'd like to be able to source this file and then refer to the functions and source file like a typical R package, say:

customSource(file='utils.R', name='my_utils')
mu_utils::foo()
mu_utils::moo()

How can this be done?

You can't. To quote from ?source :

Input is read and parsed from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment

Basically, when you source a file, all the code is run as if you typed it into your console. In your case, the functions foo and moo will be added to your current environment as if you entered them into the console.

If you want to load the functions into a specific environment, you can use the sys.source function to specify the environment to parse the sourced code in, but this still won't do what you want.

As @dww commented, the only way to do what you want is to make your file into a package. It's actually not hard at all. If you're using RStudio, just make a new project and choose "New Package". It will create the folder and the skeletons of all the files you'll need. This free book by Hadley Wickham is geared towards making packages for public distribution so it has a lot of detail you don't need, but should answer any other questions you have about the process: http://r-pkgs.had.co.nz/

You can! Not exactly like a package, but like a list! To do so, use environments:

my_utils <- base::new.env()
source("utils.R", local = my_utils)
my_utils$foo()
my_utils$moo()

Please, also read https://adv-r.hadley.nz/environments.html for a better understanding of environments.

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