Welcome to the Genome Toolbox! I am glad you navigated to the blog and hope you find the contents useful and insightful for your genomic needs. If you find any of the entries particularly helpful, be sure to click the +1 button on the bottom of the post and share with your colleagues. Your input is encouraged, so if you have comments or are aware of more efficient tools not included in a post, I would love to hear from you. Enjoy your time browsing through the Toolbox.

Monday, August 18, 2014

Rounding in R: How to Keep Trailing Zeros

The round function in R is an easy way to round a number to a desired number of digits after the decimal point.  When the final digit of the number happens to be a zero, R gets a little aggressive and chooses to drop the last zero as well.  If you want to neatly print output, this behavior can be a bit frustrating. I wish there was an option for the round function to fix this behavior for values ending in zero, but I couldn't find anything. Luckily, there is an easy work around to fix this: using the base R sprintf function.  Here is a quick example script of how to round a number and keep trailing zeros (Note: this results in converting the number to a character format).

2 comments:

  1. sprintf will do the rounding for you.
    > sprintf("%.3f",7.0503)
    [1] "7.050"

    ReplyDelete
  2. sprintf will do the rounding for you.
    > sprintf("%.3f",7.0503)
    [1] "7.050"

    ReplyDelete