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

Viewed 29

I have a character expression containing results from statistical tests and I want to parse this expression in a ggplot object. But I want the parsed expression to look identical, irrespective of what the value user might have set for scipen options.

with default scipen = 0 (good)

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)"))

with scipen = 999 (undesirable)

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)"))

Without changing options on the user's side, how can I make sure that the parsed expression is always in scientific notation?

2 Answers

You can simply quote the value to ensure it's parsed as a character string and not a numeric value:

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')"))

enter image description here

We could extract the current options and then change it

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)
Related