Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving R objects (code) in .R files (R genetic programming)

Tags:

r

I'm using R for genetic programming with the RGP package. The environment creates functions that solve problems. I want to save these functions in their own .R source files. I can't for the life of me figure out how. One way I've tried is this:

bf_str = print(bf)
save(bf_str,file="MyBestFunction.R"))

bf is simply the best fit function. I've tried it also like this:

save(bf,file="MyBestFunction.R"))

The outputted file is super weird. Its just a bunch of crazy characters

like image 894
Zeke Nierenberg Avatar asked Nov 28 '25 06:11

Zeke Nierenberg


2 Answers

You can use dump for this. It will save the assignment and the definition so you can source it later.

R> f <- function(x) x*2
R> dump("f")
R> rm(f)
R> source("dumpdata.R")
R> f
function(x) x*2

Update to respond to the OP's additional request in the comments of another answer:

You can add attributes to your function to store whatever you want. You could add a score attribute:

R> f <- function(x) x*2
R> attr(f, 'score') <- 0.876
R> dump("f")
R> rm(f)
R> source("dumpdata.R")
R> f
function(x) x*2
attr(,"score")
[1] 0.876
R> readLines("dumpdata.R")
[1] "f <-"                                     
[2] "structure(function(x) x*2, score = 0.876)"
like image 98
Joshua Ulrich Avatar answered Nov 30 '25 20:11

Joshua Ulrich


The way I understand your question, you'd like to get a text representation of the functions and save that to a file. To do that, you can divert the output of the R console using the sink function.

sink(file="MyBestFunction.R")
bf_str
sink()

Then you can source the file or open it using R or another program via your OS.

EDIT:

To append a comment to the end of the file, you could do the following:

theScore <- .876

sink(file = "MyBestFunction.R", append = TRUE)
cat("# This was a great function with a score of", theScore, "\r\n")
sink()

Depending on your setup, you might need to change \r\n to reflect the appropriate end of line characters. This should work on DOS/Windows at least.

like image 27
BenBarnes Avatar answered Nov 30 '25 20:11

BenBarnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!