如何保留R会话之间的fix

如何保留R会话之间的fix

本文介绍了如何保留R会话之间的fix()函数的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 fix()使用R v2.14.0编辑函数,则这些修正将在会话期间应用。

If I edit a function with R v2.14.0 using fix(), those fixes are applied during the session.

例如,我可能进行以下编辑以在:

For example, I might make the following edit to get a white background in a hive plot:

> library(HiveR)
> fix(plotHive)
... :%s/black/white/g
... :w
... :q
> plotHive(myHiveData)

然后,如预期的那样,我在蜂巢图中获得了白色背景。

I then get a white background in the hive plot, as expected.

但是如果我退出并重新打开R,我将丢失这些更改,并且情节再次具有黑色背景。

But if I quit and reopen R, I have lost those changes, and the plot has a black background again.

如何保留在R个会话之间使用 fix()所做的编辑?

How do I preserve the edits I make with fix() between R sessions?

编辑

如果我 source()修改后的 plotHive()函数,出现以下错误:

If I source() the modified plotHive() function, I get the following error:

> modifiedPlotHive <- source("modifiedPlotHive.R")

Error in source("modifiedPlotHive.R") :
  modifiedPlotHive.R:1160:1: unexpected '<'
1159: }
1160: <
      ^
In addition: Warning message:
In readLines(file) : incomplete final line found on 'modifiedPlotHive.R'

修改后的 plotHive()函数的最后一行是:

The final line in the modified plotHive() function is:

<environment: namespace:HiveR>

如果我在 source() -ing,然后该功能将不再起作用。

If I remove this line before source()-ing, then the function no longer works.

推荐答案

这是@joran引用的更安全的方法。

Here's the safer way of doing what you want, referenced by @joran.

接收器/源对适合处理R代码文件。但是保存到文本文件然后读回其他类型的对象可以剥夺它们的重要属性,尤其是与环境有关的属性。

The sink/source pair is fine for dealing with R code files. But saving to text files and then reading back in other types of objects can strip them of important attributes, especially those relating to environments. That's what you just experienced.

保存/加载对以R自己的二进制格式存储对象,所以很多不太可能丢失与功能相关的重要信息/环境。

The save/load pair stores objects in R's own binary format, so is much less liable to lose important information/environments attached to functions.

在此示例中,我定义了 ls ,它与基本函数的区别在于默认情况下它列出以点/句点开头的对象:

In this example, I define a personal version of ls, which differs from the base function in that it by default lists objects that start with a dot/period:

my_ls <- ls
fix(my_ls)
# 1) On the first line, change 'all.names=FALSE' to 'all.names=TRUE'
# 2) Say "Yes", I want to save the changes
save("my_ls", file="my_ls.Rdata")

# Then, in a later session, test that it works
load("my_ls.Rdata")
.TrysToHide <- 99
my_ls()
# [1] ".TrysToHide" "my_ls"

另一个要点:给修改后的函数起自己的名字要干净得多。要真正编辑打包的功能并使更改继续存在,您需要编辑源代码并重新编译该包。但是,如果要这样做,请当心,因为您可能会破坏依赖于该函数的其他打包函数的函数。

One more note: it's much cleaner to give your modified function a name of its own. To really edit a packaged function, and have the changes persist, you'd need to edit the sources and recompile the package. But if you do that, beware, as you may well break the function for other packaged functions that depend on it.

这篇关于如何保留R会话之间的fix()函数的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:06