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).
sprintf will do the rounding for you.
ReplyDelete> sprintf("%.3f",7.0503)
[1] "7.050"
sprintf will do the rounding for you.
ReplyDelete> sprintf("%.3f",7.0503)
[1] "7.050"