[R] Numbers with correct significant digits

RMan54 RMan54 at cox.net
Tue Nov 21 03:40:41 CET 2006


Using formatF with the "#" flag doesn't work all the time either (doesn't
always show trailing zero's). As in:

x <- 56.97027
formatC(x, digits=3, format="g", flag="#")

which gives " 57." instead of "57.0"

Therefore, I wrote the following function that works for me in most cases:

NumToString <- function(nval, sigdig=3, xpcut=6) {
  # Filter out zero as a special case; calculate digits after the decimal
  # from number of significant digits
  if (nval == 0) digs = sigdig - 1 else digs <- sigdig - 1 -
floor(log10(abs(nval)))
  # Can't be negative
  if (digs < 0) digs <- 0
  # Switch to scientific notation if digits after the decimal > xp
  if (digs > xpcut) { fchar <- "e"; digs <- sigdig - 1 } else fchar <- "f"
  sprintf(paste("%.", digs, fchar, sep=""), nval)
}

Optional arguments"
sigdig = number of significant digits
xpcut = if the number of digits after the decimal exceeds this cut off,
exponential (scientific) notation is used.

Example:

exvals <- c(123456.79 / (10^(0:13)))
results <- sapply(exvals, NumToString, sigdig=4)

For a number like 99.99 and 3 significant digits, rounding causes to add one
digit before the decimal, and as a resullt, 4 significant digits are shown:
"100.0" instead of "100.".



RMan54 wrote:
> 
> ....
> Since formatC is an implementation of the C-style formatting, I thought
> that a "#" as flag could work (for g and G conversions, trailing zeros are
> not removed  from  the  result  as they would otherwise be). Although not
> in the online help, this worked in R as follows:
> 
> v  <- c(9.6996, 99.99)
> formatC(v, digits=3, format="g", flag="#")
> 
> result:
> 
> "9.70" "100."
> 
> ....
> 

-- 
View this message in context: http://www.nabble.com/Numbers-with-correct-significant-digits-tf2657246.html#a7464872
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list