r - 在 R 中使用 format() 格式化数字向量

标签 r formatting format

当我尝试使用 format() 格式化数字向量时,只有第一个数字符合“digits”参数

format(c(1.508390e-06, 8.487128e-02,  4.185008e-01,  4.785161e-01, -8.332557e-01),        
    digits = 3, scientific = FALSE)
[1] " 0.00000151" " 0.08487128" " 0.41850080" " 0.47851610" "-0.83325570"

但是,如果我依次将其应用于每个元素,则会得到预期的结果。
sapply(c(1.508390e-06, 8.487128e-02,  4.185008e-01,  4.785161e-01, -8.332557e-01), FUN = function(x) { format(x,digits = 3, scientific = FALSE) } )
[1] "0.00000151" "0.0849"     "0.419"      "0.479"      "-0.833"    

我在这里错过了什么吗?

请注意,如果我设置了 Scientific = FALSE,则所有数字的格式都正确:
format(c(1.508390e-06, 8.487128e-02,  4.185008e-01,  4.785161e-01, -8.332557e-01),        
        digits = 3, scientific = TRUE)
" 1.51e-06" " 8.49e-02" " 4.19e-01" " 4.79e-01" "-8.33e-01"

最佳答案

我不确定为什么不能通过 format() 运行原子向量并得到想要的结果。它与nsmall有关参数和小数点右边的位数(这可能是未知的),我不太明白。

但看起来我们确实可以使用列表。来自 help(format) :

If x is a list, the result is a character vector obtained by applying format.default(x, ...) to each element of the list (after unlisting elements which are themselves lists), and then collapsing the result for each element with paste(collapse = ", ").



因此,只需将您的原子向量强制转换为列表,然后它就会按需要工作。
format(as.list(x), digits=3, scientific=FALSE)
# [1] "0.00000151" "0.0849"     "0.419"      "0.479"      "-0.833"   

数据:
x <- c(1.508390e-06, 8.487128e-02,  4.185008e-01,  4.785161e-01, -8.332557e-01) 

关于r - 在 R 中使用 format() 格式化数字向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50184152/

相关文章:

date - 如何定义给定日期的日期格式

r - 根据字符的出现拆分字符串

R:如何在字符串中间添加一个零

wpf - WPF DataGridCell 中的条件格式

excel - 如何动态格式化 Excel 溢出范围?

java - Android:如何正确格式化日期和时间字符串?

php - 根据 PHP 语言环境获取日期格式

Python csv.writer 控制精度

r - ggplot2 标签不会躲避 geom_col 条

使用 `ctree` 包运行 `party`,列作为因子而不是字符