Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将所有函数保存在txt文件中_R_File_Text_Output - Fatal编程技术网

R 将所有函数保存在txt文件中

R 将所有函数保存在txt文件中,r,file,text,output,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.symb

我通常在
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)
因此,简而言之,我想让随笔_4_code.txt R可读

您可以使用

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"
rm(list=ls())
#绑定到非全局环境的函数

e您可以使用.rhistore文件获取您试图捕获的信息吗?我手头没有一份副本,现在无法尝试此功能…与(副本?)相关:
 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"
e<-new.env()
load('essay_4_code.Rd', e)
as.list(e)
# $f
# function () 
# x + 1
# <environment: 0x000000000a7b2148>
# 
# $g
# function () 
# y + 1