In R, using scientific notation 10 ^, not e +

This question may have been asked, but I could not find a simple solution. Is there a way to convert a number into its scientific notation, but in the form of 10 ^, and not the default e + or E +? Thus, 1000 will become 1 * 10 ^ 3, not 1e + 3. Thank you!

+4
source share
1 answer

To print a number, you can consider it as a string and use subit to format 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"
+5
source

Source: https://habr.com/ru/post/1583889/


All Articles