0

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!

1
  • 1
    I am not aware that this is possible. You could create a package, but you would then also source all functions. Otherwise, you could put them into different files and source one file per function. Commented Feb 27, 2020 at 10:39

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Your code worked perfectly. Do you know how to print the code corresponding to that function? If I use print I get only function() print("Hello world"), but I want to get the full code hello_world <- function() print("Hello world"). If I use echo=T inside the source function I get it for both functions. How do I obtain it for one of the functions?
@JN_2605 It sounds like you want to get the actual text of the source code, which is not entirely preserved by R. Your two options are to text parse the source file (possible but tiresome and likely to be imperfect), or to "cheat" by recreating the function source like this print_source <- function(f) {x <- capture.output(f); x[1] <- paste(deparse(substitute(f)), "<-", x[1]); cat(x, sep = "\n")} You would use this by doing print_source(hello_world)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.