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

前端 未结 1 387
南笙
南笙 2020-12-07 02:29

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

相关标签:
1条回答
  • 2020-12-07 02:46

    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"
    
    0 讨论(0)
提交回复
热议问题