On 28-Apr-10 21:45:12, Steve Taylor wrote: > > Is this a bug somewhere? The format function, using a specific > number of digits, doesn't give sensible results: > > R> set.seed(2);print(x<-rexp(5)) > [1] . > R> format(x,digits=1) > [1] "1.87" "0.40" "0.15" "1.73" "0.09" > R> format(x,digits=2) > [1] "1.87" "0.40" "0.15" "1.73" "0.09" > R> format(x,digits=3) > [1] "1.8654" "0.4047" "0.1467" "1.7307" "0.0895"
Not a bug (unless you consider the documented behaviour to amount to a bug)! From: ?format digits: how many significant digits are to be used for numeric and complex 'x'. The default, 'NUL'?, uses 'getOption(digits)'. This is a suggestion: enough decimal places will be used so that the smallest (in magnitude) number has this many significant digits, And that is exactly what is happening. In your first example, the smallest number 0.08953 rounds (to 1 significant digit) to 0.09 and therefore prints as 0.09. In the second, 0.08953 rounds (to 2 significant digits) to 0.090, which can be printed without further loss of precision as 0.09 while giving the other numbers 2 significant digits. In the third, 0.08953 rounds (to 3 significant digits) to 0895 The point about the four significant digits given for the other (larger numbers) is that withg format() *all the numbers are printed to the same number of decimal places*. Hence the smallest number gets 3 signficicant digits, hence 4 decimal places. The other larger numbers will then also get 4. It looks as though, lurking behind your question, is a secret wish for a fixed number of *decimal places* (1, or 2 or 3 in your examples). For this, try formatC() (but be careful): X <- c(1.86535, 0.40475, 0.14665, 1.73071, 0.08953) formatC(X,2) # [1] "1.9" "0.4" "0.15" "1.7" "0.09" formatC(X,2,format="f") # [1] "1.87" "0.40" "0.15" "1.73" "0.09" formatC(X,3) # [1] "1.87" "0.405" "0.147" "1.73" "0.0895" formatC(X,3,format="f") # [1] "1.865" "0.405" "0.147" "1.731" "0.090" Hoping this helps! Ted. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@manchester.ac.uk> Fax-to-email: +44 (0)870 094 0861 Date: 28-Apr-10 Time: 23:12:53 ------------------------------ XFMail ------------------------------ ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.