当我尝试使用 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 applyingformat.default(x, ...)
to each element of the list (afterunlist
ing elements which are themselves lists), and then collapsing the result for each element withpaste(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/