dkrider
dkrider

Reputation: 63

Formatting a vector of numbers using format() in R

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"

Upvotes: 6

Views: 1461

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

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 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 = ", ").

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) 

Upvotes: 5

Related Questions