R使用函数内的临时选项设置 [英] R using temporary options settings inside a function

查看:182
本文介绍了R使用函数内的临时选项设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数需要我设置一个选项,即 stringsAsFactors = FALSE 。我常用的方法是在函数开始时存储现有的值。

I have a function which requires that I set an option, namely stringsAsFactors=FALSE. My all-too common approach was to store the existing value at the onset of the function

op <- option("stringsAsFactors")

在调用 return(x)确保呼叫

and before calling return(x) make sure to call

options(op)

尽管有效,但它是一个冗长而复杂的函数,可以从几个地方返回,所以我需要确保每个 return(x) options(op),或者创建一个小函数(它本身在我的函数中),它只能做到这一点:

While that works, it's a lengthy and complex function that can return from several places, so I need to either make sure every return(x) is preceded by options(op), or create a tiny function (itself inside my function) that does only that:

returnfunc< - function(x){
options(op)
return(x)
}

所以我的问题是:什么是更好的方法来做到这一点?从某种意义上说,一个会阻止该函数退出时出现错误并使参数(不适当地)被修改的问题?

So my question is: what would be a better way to do that? Specefically, one that would prevent that the function exits with an error and leave the parameter (unduly) modified?

推荐答案

on.exit 函数中完成这个操作。例如

There's a built in on.exit function that does exactly this. For example

f<-function() {
    op <- options(stringsAsFactors=FALSE)
    on.exit(options(op))

    read.table(...)
}

您可以在选项()调用中更改所需的选项,并在列表中更改之前返回所有值,容易重置。您可以将任何您想要的表达式传递给 on.exit ,这里我们只是将选项设置回原来的样子。当这个函数退出时,这将运行。有关更多信息,请参见?on.exit

You can change what ever options you want in the options() call and it returns all the values before the changes as list so it's easy to reset. You can pass whatever expression you want to on.exit, here we just set the options back to what they were. This will run when ever the function exits. See ?on.exit for more info.

这篇关于R使用函数内的临时选项设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆