Does this do what you want?
> x <- c(2.503,2.477,0.1204)
> sapply(signif(x,3), sprintf, fmt="%#.3g")
[1] "2.50" "2.48"
"0.120">
This will give you scientific notation for very large or small numbers.
At Friday 02:17 PM 3/14/2003 -0800, Don MacQueen wrote:>I need a function like signif(), but returns the rounded values as character
strings, formatted with trailing zeros where appropriate. If anyone has one, I
would sure appreciate a copy.
>
>Thanks
>-Don
>
>
>
>Details:
>
>signif() rounds a number to a specified number of significant digits, for
example:
>
>> x <- c(2.503,2.477,0.1204)
>
>> signif(x[1],3)
>[1] 2.5
>
>> signif(x[2],3)
>[1] 2.48
>
>> signif(x[3],3)
>[1] 0.12
>
>All of these are correct, numerically. But, the trailing zeros do not
display, naturally, because the R functions that format numbers for printing
have no way of knowing that trailing zeros are desired. Pretending I have the
function I need, named "fmt.signif", it would do this:
>
>> fmt.signif(x[1],3)
>[1] "2.50"
>
>> fmt.signif(x[2],3)
>[1] "2.48"
>
>> fmt.signif(x[3],3)
>[1] "0.120"
>
>>
>> signif(x,3)
>[1] "2.50" "2.48" "0.120"
>
>For now, at least, I'm willing to assume that I never want the numbers
formatted with exponential notation.
>--
>--------------------------------------
>Don MacQueen
>Environmental Protection Department
>Lawrence Livermore National Laboratory
>Livermore, CA, USA
>--------------------------------------
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help