The function 'format' is pretty good for this. Note that the 'format' call returns a character vector (which is fine if you're only going to write the number to file or the console).
Here's a simple example just using a randomly generated number:
> num <- rnorm(1, mean=10) > num [1] 10.24339We call format with digits=4 (show 4 significant digits) and nsmall=4 (display at least 4 digits after the decimal - for real/complex numbers in non-scientific format):
> format(num, digits=4, nsmall=4) [1] "10.2434"You can see that the format command rounds the numbers. This uses the IEC 60559 standard - 'go to the even digit'. So 0.5 is rounded to 0 and 1.5 is rounded to 2...
Of course, if you're used to sprintf style commands then you can also use the sprintf function for this:
> sprintf("%.4f", num) [1] "10.2434"
No comments:
Post a Comment