【问题标题】:Save all functions in an txt file将所有函数保存在文本文件中
【发布时间】:2013-01-22 15:47:40
【问题描述】:

我通常在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 可读

【问题讨论】:

  • 您能否使用 .Rhistory 文件来获取您尝试捕获的信息?我现在手头没有可以尝试的副本...
  • 相关(重复?):stackoverflow.com/q/11986574/271616

标签: r file text output


【解决方案1】:

你可以使用

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

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

编辑:

来自@JoshuaUlrich 在 cmets 中发布的相关问题:

...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

【讨论】:

    猜你喜欢
    • 2013-10-08
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多