在R中的函数环境中更改options()而不更改全局环境中的options()?

问题描述 投票:0回答:3

为了抑制数字的指数表示法,在我的全局环境中我有

options("scipen" = 100)
。为了做一些需要指数表示法的事情,我想暂时更改函数内部的此选项,例如

f <- function(x){
                 options("scipen" = -100)
                 ...
}

但是,更改函数内部的选项也会自动更改全局环境中的选项。有没有办法仅在函数内部本地更改选项?

r function global environment
3个回答
11
投票

这是一个使用的好地方

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

5
投票

withr 包可以做到这一点:

library(withr)
f <- function(x) with_options(list(scipen = -100), {
          print(x)
})
f(1.2)
## [1] 1.2e+00
getOption("scipen")
## [1] 0

0
投票

这是一篇旧帖子,但以下内容看起来很棒:

f <- function(x){
  options("scipen" = -100)
  ...
  options("scipen" = 0)
  return(output)
}

因为正常情况下,

getOption("scipen")

回归

0

希望您觉得这很有用。

© www.soinside.com 2019 - 2024. All rights reserved.