Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 360
dkrider Avatar asked May 04 '18 23:05

dkrider


People also ask

What does format () do in R?

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.

What is Nsmall R?

nsmall: is the minimum number of digits to the right of the decimal point.

How do I restrict the digits after the decimal in R?

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.


1 Answers

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) 
like image 153
Rich Scriven Avatar answered Sep 18 '22 13:09

Rich Scriven