Only original functions in .R file

I would like to be able to source()

find and load functions in a file .R

.

For example, in the Analysis.R file:

print.hw <- function() {
    print("hello world")
}

x <- 1 + 2
...

      

When I do source("Analysis.R")

, it will create a function print.hw

, but it will also assign x

what I don't want.

Does anyone have any idea? The best I could find this question:

Source only part of the file

+3


source to share


2 answers


This works without using a regular expression. It is also probably less computationally efficient than regular solutions. It creates a new environment, the source of the entire file, and then only returns the functions back to the global environment.



SourceFunctions<-function(file) {
  MyEnv<-new.env()
  source(file=file,local=MyEnv)
  list2env(Filter(f=is.function,x=as.list(MyEnv)),
           envir=parent.env(environment()))
}

      

+6


source


I find it good practice to strip the test code down to the end of the source files (as is usually the case with Python) and then invoke them using external scripts or packages (like testthat ). Hadley dplyr can give you a link.



0


source







All Articles