Only source functions in a .R file

前端 未结 2 660
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 20:28

I would like source() to only find and load functions within a .R file.

For example, in the file Analysis.R:

print.hw <         


        
相关标签:
2条回答
  • 2020-12-10 21:16

    I think its a good practice to separate test code before the end of source files (as we usually do in Python) and then invoke them with external scripts or packages (like testthat). Hadley's dplyr may give you a reference.

    0 讨论(0)
  • 2020-12-10 21:27

    This works without using regex. It's also probably less computationally efficient than regex solutions. It creates a new environment, sources the entire file, then returns only 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()))
    }
    
    0 讨论(0)
提交回复
热议问题