我正在使用R进行遗传编程和RGP包.环境创建解决问题的功能.我想将这些函数保存在自己的.R源文件中.我不能为我的生活弄清楚如何.我试过的一种方法是:
bf_str = print(bf)
save(bf_str,file="MyBestFunction.R"))
Run Code Online (Sandbox Code Playgroud)
bf只是最合适的功能.我也尝试过这样:
save(bf,file="MyBestFunction.R"))
Run Code Online (Sandbox Code Playgroud)
输出的文件非常奇怪.它只是一堆疯狂的角色
你可以用dump
它.它将保存分配和定义,以便您source
以后可以使用它.
R> f <- function(x) x*2
R> dump("f")
R> rm(f)
R> source("dumpdata.R")
R> f
function(x) x*2
Run Code Online (Sandbox Code Playgroud)
更新以在另一个答案的评论中回应OP的附加请求:
您可以向函数添加属性以存储您想要的任何内容.您可以添加一个score
属性:
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)"
Run Code Online (Sandbox Code Playgroud)
我理解你的问题的方式,你想得到函数的文本表示,并将其保存到文件中.为此,您可以使用该sink
功能转移R控制台的输出.
sink(file="MyBestFunction.R")
bf_str
sink()
Run Code Online (Sandbox Code Playgroud)
然后你可以source
通过你的操作系统使用R或其他程序打开文件或打开它.
编辑:
要将注释附加到文件末尾,您可以执行以下操作:
theScore <- .876
sink(file = "MyBestFunction.R", append = TRUE)
cat("# This was a great function with a score of", theScore, "\r\n")
sink()
Run Code Online (Sandbox Code Playgroud)
根据您的设置,您可能需要更改\r\n
以反映适当的行尾字符.这应该至少适用于DOS/Windows.
归档时间: |
|
查看次数: |
12143 次 |
最近记录: |