【问题标题】:Convert a numeric vector to scientific format without changing the mode in R将数值向量转换为科学格式而不更改 R 中的模式
【发布时间】:2020-05-16 15:40:36
【问题描述】:

我想在不将其模式更改为字符的情况下将数值向量转换为科学格式。解决方案herehere 将模式更改为字符。我尝试了以下方法:

x <- c(1.0004, 2.2223,4, 509703045845, 0.0002)
mode(x)
#first attempt
x1 <- formatC(x, format = "e")
mode(x1)
as.numeric(x1)

#second attempt
x2 <- format(x, scientific = TRUE)
mode(x2)
as.numeric(x2)

转换为数字不保留科学显示。我想要一个将显示更改为科学但保留数字模式的解决方案。

【问题讨论】:

  • 接受的答案确实表明要更改options,因为这是一个显示问题?

标签: r formatting type-conversion


【解决方案1】:

FormatFormatC 旨在获得所需形状的字符。您的数字显示不会受到影响。此外,在此处转换为字符并返回为数字会影响您的数字!考虑使用options()$scipenfirst of your linked solutions,这实际上是将数字显示更改为R 的唯一选项。scipen 来自scientific 和penalty,见?options

x <- c(1.0004, 2.2223,4, 509703045845, 0.0002)

getOption("scipen")  ## displays defaults
# [1] 5
x
# [1] 1.00040e+00 2.22230e+00 4.00000e+00 5.09703e+11 2.00000e-04
as.numeric(format(x, scientific = TRUE))  ## convert there and back
# [1] 1.00040e+00 2.22230e+00 4.00000e+00 5.09703e+11 2.00000e-04

两者相同(?)。

但是:

os <- options(scipen=50)  ## set scipen and store old scipen
x
# [1]         1.0004          2.2223       4.0000     509703045845.0000    0.0002
as.numeric(format(x, scientific = TRUE))  ## convert there and back
# [1]         1.0004          2.2223       4.0000     509703045845.0000    0.0002

所以实际上什么都没有发生,来回转换是 1. 一个 false 解决方案,

options(os)  ## restore old scipen

2.偏向您的数字,如下所示:

all.equal(x, as.numeric(format(x, scientific = TRUE)))
# [1] "Mean relative difference: 0.00000008994453"

注意:options 会在您重新启动 R 时重置为存储在您的 Rprofile.site 中的默认值,所以不要惊慌 ;-)

【讨论】:

    【解决方案2】:

    好吧,在一些包中可能有一个函数,但为什么不写你自己的简单函数呢?

    to_scientific <- function(x){
      x <- format(x, scientific = TRUE)
      as.numeric(x)
    }
    to_scientific(x)
    # [1] 1.00040e+00 2.22230e+00 4.00000e+00 5.09703e+11 2.00000e-04
    

    【讨论】:

    • 不错的尝试,但这是一个 false 解决方案,请参阅我的答案。
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2015-05-06
    • 1970-01-01
    • 2018-12-12
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多