R: Original function by name / Import a subset of functions

I have a question with importing functions.

Let's say I have an R script called "functions" that looks like this:

mult <- function(x,y){

   return(x*y)

}

divide <- function(x,y){

   return(x/y)

}

I am currently importing all functions in a script:

source(file="C:\\functions.R",echo=FALSE)

The problem is that the (actual) R script is getting very large.

Is there a way to import only the "mult" function?

I looked at evalSource / insertSource, but my code did not work:

insertSource("C:\\functions.R", functions="mult")  
+4
source share
2 answers

It looks like your code will work with a slight change: first define an empty object for the function you want to load, then use insertSource.

mult <- function(x) {0}
insertSource("C:\\functions.R", functions="mult") 
mult 

What gives:

Object of class "functionWithTrace", from source
function (x, y) 
{
    return(x * y)
}

## (to see original from package, look at object@original)

mult , , , insertSource, mult <- mult@.Data, mult .

, modules github, R- . , , , .

+4

, .

:

LoadFunction <- function(file,...) {

  dots <- match.call(expand.dots = FALSE)$...
  dots <- sapply(dots, as.character)

  output <- lapply(dots, function(x,file){eval(parse(text=paste(x," <- function(x) {0}",sep="")),envir = .GlobalEnv)
                                          suppressMessages(insertSource(file, functions=x))
                                          eval(parse(text=paste(x," <- ",x,"@.Data",sep="")),envir = .GlobalEnv) },file=file)

}


UnloadFunction <- function(...) {

  dots <- match.call(expand.dots = FALSE)$...
  dots <- sapply(dots, as.character)

  output <- lapply(dots, function(x,file){eval(parse(text=paste("rm(",x,",envir = .GlobalEnv)",sep="")))},file=file)

}

:

LoadFunction(file="C:\\functions.R",mult,divide)
UnloadFunction(mult,divide)

- :

LoadFunction2 <- function(file,function_name) {

  eval(parse(text=paste(function_name," <- function(x) {0}",sep="")),envir = .GlobalEnv)
  suppressMessages(insertSource(file, functions=function_name))
  eval(parse(text=paste(function_name," <- ",function_name,"@.Data",sep="")),envir = .GlobalEnv)         

}

UnloadFunction2 <- function(function_name) {

  eval(parse(text=paste("rm(",function_name,",envir = .GlobalEnv)",sep="")))

}

:

LoadFunction2(file="C:\\functions.R","mult")
LoadFunction2(file="C:\\functions.R","divide")
UnloadFunction2("mult")
UnloadFunction2("divide")
+3

Source: https://habr.com/ru/post/1536658/


All Articles