Home > OS >  How does the digits parameter in R's prettyNum() function work?
How does the digits parameter in R's prettyNum() function work?

Time:02-23

In R I'm using the prettyNum() function to format some numbers but I'm having a hard time getting the number of digits I want. The help docs say:

the desired number of digits after the decimal point (format = "f") or significant digits (format = "g", = "e" or = "fg").

Default: 2 for integer, 4 for real numbers. If less than 0, the C default of 6 digits is used. If specified as more than 50, 50 will be used with a warning unless format = "f" where it is limited to typically 324. (Not more than 15–21 digits need be accurate, depending on the OS and compiler used. This limit is just a precaution against segfaults in the underlying C runtime.)

To me, this seems to mean that prettyNum(404.5142, digits = 2) should give me "404.51" but in reality it produces "405". Can someone explain how to get it to round to a fixed number (say 2) of digits after the decimal place? I'd like it to include tailing 0s too.

CodePudding user response:

The help file for prettyNum is also documenting formatC, to which the parameter digits belongs. The prettyNum function does not have a parameter called digits.

The reason why this doesn't result in an error is that your argument digits is being passed via ... to format.

...       arguments passed to format.

In format, the parameter digits is different to the digits parameter in formatC. It means the number of significant digits, not the number of digits after the decimal point. Yes, this is a bit confusing in the documents, but it means for example that you could do:

prettyNum(404.5142, digits = 5)
#> [1] "404.51"

However, this will give you the wrong number of digits if you do, for example:

prettyNum(44.5142, digits = 5)
#> [1] "44.514"

And therefore you would be safer to use something like formatC, which allows

formatC(404.5142, format = "f", digits = 2)
#> [1] "404.51"

and

formatC(44.5142, format = "f", digits = 2)
#> 1] "44.51"

Which seems to be what you are looking for.

  •  Tags:  
  • r
  • Related