将所有函数保存在文本文件中

时间:2013-01-22 15:47:41

标签: r file text output

我通常在R中运行大量模拟。 在模拟之间,R的某些部分 代码会改变。通常,我会一直陪伴着  模拟结果包含一个.txt文件 每个函数的定义 模拟。为了制作那个.txt文件,我只是 运行这一行:

for(j in 1:length(ls()))    print(c(ls()[j],eval(as.symbol(ls()[j]))))
out<-capture.output(for(j in 1:length(ls()))    print(c(ls()[j],eval(as.symbol(ls()[j])))))
cat(out,file=paste("essay_4_code.txt",sep=""),sep="\n",append=FALSE)

在我的环境中加载所有功能后立即执行。 在结果文本文件中,R函数 不是R可以解释为函数的格式。 要理解原因,这里有一个简单的例子:

rm(list=ls())
foo1<-function(x){
  sin(x)+3
}
foo2<-function(x){
  cos(x)+1
}
foo3<-function(x){
  cos(x)+sin(x)
}

会产生:

[[1]]
[1] "foo1"

[[2]]
function (x) 
{
    sin(x) + 3
}

[[1]]
[1] "foo2"

[[2]]
function (x) 
{
    cos(x) + 1
}

[[1]]
[1] "foo3"

[[2]]
function (x) 
{
    cos(x) + sin(x)
}

所以,简而言之,我想让essay_4_code.txt R-readable

1 个答案:

答案 0 :(得分:4)

您可以使用

dump(lsf.str(), file="essay_4_code.R")

这将创建一个.R文件,其中包含当前搜索空间中的所有函数定义。

编辑:

来自@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