Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, using scientific notation 10^ rather than e+

Tags:

r

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!

like image 464
xiaoxiao87 Avatar asked Apr 22 '15 00:04

xiaoxiao87


1 Answers

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"
like image 143
Molx Avatar answered Oct 05 '22 23:10

Molx