2

I typically run a lot of simulations in R. In between simulations, some parts of the R code would change. Typically, i keep alongside the simulation results a .txt file containing the definition of every function used in that simulation. To make that .txt file, i simply run this line:

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)

right after loading all the function in my env. In the resulting text file however the R functions are not in a format that R can interpret as functions. To understand why, here is a simple example:

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

would yield:

[[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)
}

So, in a nutshell, i would want to make essay_4_code.txt R-readable

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
user189035
  • 5,589
  • 13
  • 52
  • 112

1 Answers1

5

You could use

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

This will create an .R file with all of the function definitions in the current search space.

edit:

from the related question posted by @JoshuaUlrich in the comments:

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

Alternatively, you can you use the save function to save the function in a binary format readable with the load function. This preserves your functions' environment bindings, but you lose the ability to read the resulting file yourself.

 do.call(save, c(as.list(lsf.str()), file='essay_4_code.Rd'))

Upon loading in a fresh session, functions previously bound to the global environment will be bound to the current global environment, while functions that were bound to a different environment will carry that environment with them.

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"

And if you just wanted to inspect the bodies of the function in '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
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113