When I attempt to format a vector of numbers using format(), only the first number respects the "digits" argument
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"
However, if I sapply it to each element in turn, I get the expected result.
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"
Am I missing something here?
Note that if I set scientific = FALSE, then all numbers are formatted correctly:
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"
The function format() allows you to format an R object for pretty printing. Essentially, format() treats the elements of a vector as character strings using a common format. This is especially useful when printing numbers and quantities under different formats.
nsmall: is the minimum number of digits to the right of the decimal point.
To format all decimal places in an R vector and data frame, we can use formattable function of formattable package where we can specify the number of digits after decimal places.
I'm not exactly sure why you can't run the atomic vector through format()
and get the desired result. It has something to do with the nsmall
argument and the number of digits to the right of the decimal (which is probably unknown) which I don't quite understand.
But it does look like we can use a list. From 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 = ", ")
.
So just coerce your atomic vector to a list, then it will work as desired.
format(as.list(x), digits=3, scientific=FALSE)
# [1] "0.00000151" "0.0849" "0.419" "0.479" "-0.833"
Data:
x <- c(1.508390e-06, 8.487128e-02, 4.185008e-01, 4.785161e-01, -8.332557e-01)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With