将长代码文件转换为单独的文件

时间:2017-12-28 22:11:43

标签: r

我有两个很长的R文件,它们有很多函数定义,并且它们之间有一些不规则的注释。是否有任何R函数将每个函数定义移动到单独的R文件中?用函数名称命名新文件会很不错。

1 个答案:

答案 0 :(得分:3)

包含所有功能的文件内容(让我们称之为tuttifrutti.R)可能是这样的:

fun1 <- function(x) {
  # comment
  x * x
}

fun2 <- function(x) {
  # comment
  x/2
}

然后你可以收集所有功能并将它们打印到同名文件。

localenv <- new.env()

source("tuttifrutti.R", local = localenv)
sapply(localenv, print)

sapply(names(localenv), FUN = function(x, en) {
  dump(x, file = sprintf("%s.R", x), envir = en)
}, en = localenv)