你可以使用
dump(lsf.str(), file="essay_4_code.R")
这将创建一个 .R 文件,其中包含当前搜索空间中的所有函数定义。
edit:
来自 @JoshuaUlrich 在评论中发布的相关问题:
...dump("f") will only save the function definition of f, and not its environment.
If you then source the resulting file, f will no longer work correctly [if it
depends on variables in the environment in was previously bound to].
或者,您可以使用save
函数以可读的二进制格式保存函数load
功能。这保留了函数的环境绑定,但您失去了自己读取结果文件的能力。
do.call(save, c(as.list(lsf.str()), file='essay_4_code.Rd'))
在新会话中加载时,先前绑定到全局环境的函数将绑定到当前全局环境,而绑定到不同环境的函数将携带该环境。
rm(list=ls())
# function bound to non-global environment
e <- new.env()
e$x <- 10
f <- function() x + 1
environment(f) <- e
# function bound to global environment
y <- 20
g <- function() y + 1
# save functions
do.call(save, c(as.list(lsf.str()), file='essay_4_code.Rd'))
# fresh session
rm(list=ls())
load('essay_4_code.Rd')
f()
# [1] 11
g()
# Error in g() : object 'y' not found
y <- 30
g()
# [1] 31
ls()
# [1] "f" "g" "y"
如果您只想检查“eassay_4_code.Rd”中的函数体:
e<-new.env()
load('essay_4_code.Rd', e)
as.list(e)
# $f
# function ()
# x + 1
# <environment: 0x000000000a7b2148>
#
# $g
# function ()
# y + 1