[R] Built-in function for extracting mantissa and exponent of a numeric

Duncan Murdoch murdoch.duncan at gmail.com
Sun Jun 23 13:08:04 CEST 2013


On 13-06-23 5:54 AM, Søren Højsgaard wrote:
> Dear all,
>
> Given a number
>
> x<-1.234e12
>
> is there a built-in function for extracting 1.234 and 12 ?

I don't think so, but it is not hard to build them from log10:

mantissa <- function(x) {
   if (x == 0) 0
   else {
     log <- log10(abs(x))
     10^(log - floor(log))
   }
}

exponent <- function(x) {
   if (x == 0) 0
   else floor(log10(abs(x)))
}

Duncan Murdoch



>
> The following "hack" seems clumpsy:
>
>> a<-strsplit(format(x, scientific=T),"e")[[1]]
>> a
> [1] "1.234" "+12"
>> as.numeric(a[1])
> [1] 1.234
>> as.integer(a[2])
> [1] 12
>
> Regards
> Søren
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list