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
You could use
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:
Alternatively, you can you use the
savefunction to save the function in a binary format readable with theloadfunction. This preserves your functions’ environment bindings, but you lose the ability to read the resulting file yourself.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.
And if you just wanted to inspect the bodies of the function in ‘eassay_4_code.Rd’: