2

For example if i have

a <- 10203.102

integer: 10203 decimal: 0.102

I would like a procedure to store the parts of the number into two separate vectors, the same as if I do the following:

integerpart <- c(1, 0, 2, 0, 3)

decimalpart <- c(0, 1, 0, 2)
J_F
  • 9,956
  • 2
  • 31
  • 55
Ricardo
  • 35
  • 3
  • 1
    How general do you need to be? `integerpart = trunc(a)`, `decimalpart = a %% 1` will work for positive `a`. `decimalpart = sign(a) * (abs(a) %% 1)` should work for negative `a` as well. You could use `strsplit` on those to break out individual digits. – Gregor Thomas Oct 24 '16 at 16:48
  • I do think you'll be disappointed with the decimal part results however, see [Why are these numbers not equal](http://stackoverflow.com/q/9508518/903061) to learn about the problems of floating point precision and why you'll probably get many more decimal part digits than you think are really there. – Gregor Thomas Oct 24 '16 at 16:53
  • 2
    Another option, `strsplit(strsplit(as.character(a), split = "\\.")[[1]], split = "")` – Gregor Thomas Oct 24 '16 at 16:56
  • This would also get you pretty close: `lapply(strsplit(as.character(a), split="\\."), strsplit, split="")` as a list of the two vectors. – lmo Oct 24 '16 at 17:02
  • 1
    we golfin? `strsplit(scan(t=sub('\\.',' 0',a),w=''),'')` – rawr Oct 24 '16 at 17:04

1 Answers1

0

Here is a simple function that does the trick even though the output is not perfect (maybe because the decimal part has a lot of 0.102000000000771). a is the number you want

a <- 10203.102

split_decimal <- function(a, n = 2) {
                      paste0("integer: ",
                             ifelse(a - (a %% 1) == 0, a, a - (a %% 1)
                                    ) ,
                             ", ",
                             "decimal: ",
                             round((a %% 1), n)
                             )
                    }

split_decimal(a, 3)
SabDeM
  • 7,050
  • 2
  • 25
  • 38