使用options()和getOption()真正如何保存,更改和恢复选项

时间:2016-12-08 18:31:39

标签: r

在来自@Hiemstra(Paul Hiemstra)的post消息之后,我试图重现类似的保存方式,使用options(),getOption()函数更改R中的选项的恢复:

print("Print options. Expected null/empty values")
print(paste("[cats.funName, cats.value]=[", getOption("cats.funName"), ",",
    getOption("cats.value"), "]", sep=""))
print("Saving the options...")
system("rm 'default_options.rda'")
default_options = options()
save(default_options, file = "default_options.rda")
print("Verify the rda file was created...")
system("ls 'default_options.rda'")
rm(default_options)
print(ls())
print("Changing the options...")
options("cats.funName" = "my_functionName")
options("cats.value" = sqrt(2))
print(paste("[cats.funName, cats.value]=[", getOption("cats.funName"), ",",
    getOption("cats.value"), "]", sep = ""))
print("Restoring original options...")
print(load("default_options.rda"))
print("variables defined after loading default_options: ls()...")
print(ls())
options(default_options)
print("Printing the options, expected null/empty values...")
print(paste("[cats.funName, cats.value]=[", getOption("cats.funName"), ",",
    getOption("cats.value"), "]", sep = ""))

我得到以下输出:

[1] "Print options. Expected null/empty values"
[1] "[cats.funName, cats.value]=[,]"
[1] "Saving the options..."
[1] "Verify the rda file was created..."
default_options.rda
character(0)
[1] "Changing the options..."
[1] "[cats.funName, cats.value]=[my_functionName,1.4142135623731]"
[1] "Restoring original options..."
[1] "default_options"
[1] "variables defined after loading default_options: ls()..."
[1] "default_options"
[1] "Printing the options, expected null/empty values..."
[1] "[cats.funName, cats.value]=[my_functionName,1.4142135623731]"
> 

我预计空值,因为之前没有保存过猫*属性。

1 个答案:

答案 0 :(得分:1)

默认情况下,带有列表的options()将仅设置列表中找到的值。它不会删除列表中未找到的值。您可以使用

找到列表中未包含的所有选项列表
to_remove <- setdiff(names(options()), names(default_options))

然后用

删除它们
options(Map(function(x) NULL, to_remove))