JN_2605
JN_2605

Reputation: 145

loading a function using source function

I have a script in R with different functions. I want to use source() to load them in another script, but I only want to load one of them. I know it is possible to select the numbers of the lines you want to source, but I would like to use the name of the function.

For example, suppose I have a file "script.R" including the functions "fun1", "fun2" and "fun3". How do I load "fun1" in my new script using source and the name of the function?

Many thanks in advance!

Upvotes: 0

Views: 770

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

Suppose I have this file called "01_script.R":

hello_world <- function() print("Hello world")

goodbye_world <- function() print("Goodbye world")

Then I can use the following function to source the whole script, but select only the function I want to be copied to the calling environment:

source_func <- function(file, func)
{
  tmp_env <- new.env()
  source(file, local = tmp_env)
  assign(func, get(func, envir = tmp_env), envir = parent.frame())
}

So I can do the following:

ls()
#> [1] "source_func"
source_func("01_script.R", "hello_world")
ls()
#> [1] "hello_world" "source_func"
hello_world()
#> [1] "Hello world"
goodbye_world()
#> Error in goodbye_world() : could not find function "goodbye_world"

Upvotes: 1

Related Questions