Format 和FormatC 旨在获得所需形状的字符。您的数字显示不会受到影响。此外,在此处转换为字符并返回为数字会影响您的数字!考虑使用options()$scipen 的first 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 中的默认值,所以不要惊慌 ;-)