函数 write() 与数字符号不一致

Function write() inconsistent with number notation

考虑以下脚本:

list_of_numbers <- as.numeric()
for(i in 1001999498:1002000501){
  list_of_numbers <- c(list_of_numbers, i)
}
write(list_of_numbers, file = "./list_of_numbers", ncolumns = 1)

生成的文件如下所示:

[user@pc ~]$ cat list_of_numbers
1001999498
1001999499
1.002e+09
...
1.002e+09
1.002e+09
1.002e+09
1002000501

我发现了几个范围,其中 R 打印的数字格式不一致。

现在我有以下问题:

这是错误还是此行为有实际原因? 为什么只是在某些范围内,为什么不是每个高于 x 的数字?

我知道如何解决这个问题:

options(scipen = 1000)

但是还有比设置全局选项更优雅的方法吗?无需将其转换为数据框并更改格式。

这不是错误,R 选择了最短的表示。

更准确地说,在 ?options 中可以阅读:

fixed notation will be preferred unless it is more than scipen digits wider.

所以当scipen为0(默认值)时,首选最短的表示法。

请注意,您可以使用 format(x, scientific = TRUE).

获得数字 x 的科学记数法

你的情况:

  • 1001999499 的长度为 10 个字符,而其科学计数法 1.001999e+09 更长(12 个字符),因此保留十进制表示法。
  • 1001999500:科学计数法是1.002e+09,比较短
  • ......................(科学计数法保持等于 1.002e+09,因此更短)
  • 1002000501: 1.002001e+09 更长。

您可能会问:为什么 1001999500 格式为 1.002e+09 而不是 1.0019995e+09?很简单,因为还有一个控制有效数字位数的选项。它被命名为digits,默认值为7。由于1.0019995有8位有效数字,因此向上取整为1.002

确保在不更改全局选项的情况下保留十进制表示法的最简单方法可能是使用 format:

write(format(list_of_numbers, scientific = FALSE, trim = TRUE), 
      file = "./list_of_numbers")

旁注:您不需要循环来生成 list_of_numbers(顺便说一句,它不是列表而是向量)。只需使用:

list_of_numbers <- as.numeric(1001999498:1002000501)