发布于 2020-05-16 16:25:38
Format
和FormatC
用于获得所需形状的字符。你的数字显示不会受到影响。此外,转换到字符那里和返回数字将偏见你的数字!考虑使用first of your linked solutions options()$scipen
,这实际上是将数字显示改为R的唯一选项,scipen
来自_sci_entific和_pen_alty,参见?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。是一个错误的解决方案,
options(os) ## restore old scipen
2.将对数字进行偏置,如下所示:
all.equal(x, as.numeric(format(x, scientific = TRUE)))
# [1] "Mean relative difference: 0.00000008994453"
注意:重新启动R时, options
重置为存储在Rprofile.site
中的默认值,因此不要惊慌;)
发布于 2020-05-16 15:51:45
在某些包中可能有这样的函数,但是为什么不直接编写自己的简单函数呢?
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
https://stackoverflow.com/questions/61839350
复制相似问题