Programmer1 - 3 months ago 56

R Question

I need to sort the decimal value of a number in descending order so that I will be able to add one to the number with the highest decimal value.

For example I have:

1.5, 2.4, 6.7 and I need the total of these three numbers to be 11. Rounding to 1 integer I will obtain 1,2,6. I need to add 2 in order to reach 11.

I would like to add 1 to the numbers having the highest decimal places i.e to 1 and 6 and then I end up with 2+2+7 which adds up to 11. Is it possible to do this in R? Is it possible to access decimal places?

Answer

The decimals can be computed like this:

```
decimals <- function(x) x-floor(x)
```

examples:

```
> decimals(3)
[1] 0
> decimals(3.123)
[1] 0.123
> decimals(3.98)
[1] 0.98
> decimals(5.5)
[1] 0.5
> decimals(1222.99999)
[1] 0.99999
> decimals(rnorm(10,sd=10)) # it is already vectorized
[1] 0.08650212 0.13957433 0.37153204 0.12571212 0.97804479 0.47355533
[7] 0.32244821 0.78559509 0.25393115 0.02253588
```