解析字符中的数值,因为它们与 `scipen` 的值无关

parsing numeric values in character as they are irrespective of value of `scipen`

我有一个包含统计测试结果的字符表达式,我想在 ggplot 对象中解析该表达式。但我希望解析后的表达式看起来相同,而不管用户可能为 scipen 选项设置的值是什么。

默认 scipen = 0(好)

library(ggplot2)

# plot is just for illustration and has nothing to do with the statistics being displayed
ggplot(mtcars, aes(wt, mpg)) + geom_smooth() + geom_point() + 
  labs(subtitle = parse(text = "list(~chi['gof']^2~(8)==617.445, ~italic(p)==4.15e-128)"))

scipen = 999(不受欢迎)

library(ggplot2)
options(scipen = 999)

# plot is just for illustration and has nothing to do with the statistics being displayed
ggplot(mtcars, aes(wt, mpg)) + geom_smooth() + geom_point() + 
  labs(subtitle = parse(text = "list(~chi['gof']^2~(8)==617.445, ~italic(p)==4.15e-128)"))

在不更改用户端选项的情况下,如何确保解析的表达式始终采用科学记数法?

您可以简单地引用该值以确保它被解析为字符串而不是数值:

library(ggplot2)

options(scipen = 999)

ggplot(mtcars, aes(wt, mpg)) + geom_smooth() + geom_point() + 
  labs(subtitle = parse(text = "list(~chi['gof']^2~(8)==617.445, ~italic(p)=='4.15e-128')"))

我们可以提取当前选项然后进行更改

op <- options()$scipen
options(scipen = 0)
ggplot(mtcars, aes(wt, mpg)) + geom_smooth() +
      geom_point() + 
      labs(subtitle = parse(text = "list(~chi['gof']^2~(8)==617.445, ~italic(p)==4.15e-128)"))

# // change it to current options
options(scipen = op)