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

前端 未结 4 1891
囚心锁ツ
囚心锁ツ 2021-01-21 17:02

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

4条回答
  •  无人及你
    2021-01-21 17:33

    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)"
    

提交回复
热议问题