1

I want to call a specific function that I built in a script in R into another script. I don't want to use the source function since it will evaluate the script where the function to be call is stored. Do you know any option to perform this job?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Vin
  • 11
  • 1
  • 1
    Build a package ... – Roland Jul 29 '22 at 07:50
  • I usually save all the auxiliar functions into a script and then use `source` function. You probably do not want to use it because you have examples, . . . I recomend you to create a scritp where only the functions are defined. – R18 Jul 29 '22 at 08:05
  • The source command accepts a connection, so you could plausibly open the script file, send only the lines related to your function to a new connection, and source that - but this is madness, just move or copy your function to a separate file. – Ottie Jul 29 '22 at 08:17

1 Answers1

0

From this answer, The below checks where in your source file you define functions, and evaluates these lines only.

cmds <- parse("fakeload.R")
assign.funs <- sapply(cmds, function(x) {
   if(x[[1]]=="<-") {
       if(x[[3]][[1]]=="function") {
           return(TRUE)
       }
   }
   return(FALSE)
})
eval(cmds[assign.funs])

However, this is not the right way to do this in R. Write a script with only functions that you can reuse as many times as you want in other scripts using source, without the need of defining more logic (functions to call functions).

When you'll want to load the same function into another script for example, you'll have to copy/paste this code again. If many scripts use the same function, modifying this "function-loading" logic will cause you some headaches.

fair warning ;)

gaut
  • 5,771
  • 1
  • 14
  • 45