Only source functions in a .R file

2020-02-06 04:08发布

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

For example, in the file Analysis.R:

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

x <- 1 + 2
...

When I source("Analysis.R"), it will create the function print.hw but also assign x, which I do not want.

Anyone have any ideas? The best I could find was this question:

Source only part of a file

标签: r
2条回答
你好瞎i
2楼-- · 2020-02-06 04:36

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()))
}
查看更多
贼婆χ
3楼-- · 2020-02-06 04:39

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.

查看更多
登录 后发表回答