为了抑制数字的指数表示法,在我的全局环境中我有
options("scipen" = 100)
。为了做一些需要指数表示法的事情,我想暂时更改函数内部的此选项,例如
f <- function(x){
options("scipen" = -100)
...
}
但是,更改函数内部的选项也会自动更改全局环境中的选项。有没有办法仅在函数内部本地更改选项?
这是一个使用的好地方
on.exit()
。它的优点是确保在退出函数调用的评估框架之前将选项重置为其原始值(存储在oo
中)——即使该退出是错误的结果。
f <- function(x) {
oo <- options(scipen = -100)
on.exit(options(oo))
print(x)
}
## Try it out
1111
## [1] 1111
f(1111)
## [1] 1.111e+03
1111
## [1] 1111
withr 包可以做到这一点:
library(withr)
f <- function(x) with_options(list(scipen = -100), {
print(x)
})
f(1.2)
## [1] 1.2e+00
getOption("scipen")
## [1] 0
这是一篇旧帖子,但以下内容看起来很棒:
f <- function(x){
options("scipen" = -100)
...
options("scipen" = 0)
return(output)
}
因为正常情况下,
getOption("scipen")
回归
0
希望您觉得这很有用。