【问题标题】:In R, using scientific notation 10^ rather than e+在 R 中,使用科学记数法 10^ 而不是 e+
【发布时间】:2015-04-22 00:26:24
【问题描述】:

可能有人问过这个问题,但我没有找到一个简单的解决方案。有没有办法将数字转换为其科学记数法,但以 10^ 的形式而不是默认的 e+ 或 E+?所以 1000 会变成 1*10^3 而不是 1e+3。谢谢!

【问题讨论】:

  • 你想以这种格式保存数字还是直接打印它们?
  • 在哪里?只是在控制台中?总是?对于每个数字?
  • 嗨!好点子。我猜控制台会工作。最终我希望将数字打印到情节中,但如果它适用于控制台,情节应该显示与我认为相同的内容。此外,这个问题通常发生在像 1000000 这样非常大的数字上,因为 R 会自动将其转换为 1e+6。
  • 因为您写“最终我希望将数字打印到情节”,this Q&A 似乎相关。

标签: r


【解决方案1】:

要打印数字,您可以将其视为字符串并使用sub 重新格式化:

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
}

一些例子:

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

【讨论】:

    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多