This question may have been asked, but I didn't manage to find a straightforward solution. Is there a way to convert a number to its scientific notation, but in the form of 10^ rather than the default e+ or E+? So 1000 would become 1*10^3 rather than 1e+3. Thanks!
Asked
Active
Viewed 4,074 times
9
-
Do you want to save the numbers in this format or simply print them like that? – Molx Apr 22 '15 at 00:42
-
Where? just in the console? Always? For every number? – MrFlick Apr 22 '15 at 00:42
-
Hi! Good point. I guess console would work. Ultimately I want the number to be printed to a plot, but if it works for the console, the plot should show the same thing I think. Also, this problem usually happens for very large numbers like 1000000, as R will automatically convert it into 1e+6. – xiaoxiao87 Apr 22 '15 at 00:47
-
Because you write "Ultimately I want the number to be printed to a plot", [this Q&A](http://stackoverflow.com/questions/22833294/force-r-to-write-scientific-notations-as-n-nn-x-10-n-with-superscript/22833996#22833996) seems relevant. – Henrik Apr 22 '15 at 06:31
1 Answers
11
To print the number you can treat it as a string and use sub
to reformat it:
changeSciNot <- function(n) {
output <- format(n, scientific = TRUE) #Transforms the number into scientific notation even if small
output <- sub("e", "*10^", output) #Replace e with 10^
output <- sub("\\+0?", "", output) #Remove + symbol and leading zeros on expoent, if > 1
output <- sub("-0?", "-", output) #Leaves - symbol but removes leading zeros on expoent, if < 1
output
}
Some examples:
> changeSciNot(5)
[1] "5*10^0"
> changeSciNot(-5)
[1] "-5*10^0"
> changeSciNot(1e10)
[1] "1*10^10"
> changeSciNot(1e-10)
[1] "1*10^-10"

Molx
- 6,816
- 2
- 31
- 47