use*_*035 2 text r file 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)
Run Code Online (Sandbox Code Playgroud)
在我的环境中加载所有功能之后。然而,在生成的文本文件中,R 函数不是 R 可以解释为函数的格式。为了理解原因,这里有一个简单的例子:
rm(list=ls())
foo1<-function(x){
sin(x)+3
}
foo2<-function(x){
cos(x)+1
}
foo3<-function(x){
cos(x)+sin(x)
}
Run Code Online (Sandbox Code Playgroud)
会产生:
[[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)
}
Run Code Online (Sandbox Code Playgroud)
所以,简而言之,我想让essay_4_code.txt R 可读
你可以用
dump(lsf.str(), file="essay_4_code.R")
Run Code Online (Sandbox Code Playgroud)
这将创建一个 .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].
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用该save
函数以该函数可读的二进制格式保存该load
函数。这会保留函数的环境绑定,但您无法自己读取生成的文件。
do.call(save, c(as.list(lsf.str()), file='essay_4_code.Rd'))
Run Code Online (Sandbox Code Playgroud)
在新会话中加载时,先前绑定到全局环境的函数将绑定到当前全局环境,而绑定到不同环境的函数将携带该环境。
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"
Run Code Online (Sandbox Code Playgroud)
如果您只想检查“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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1006 次 |
最近记录: |