Reformatting numeric values without coercing a character
Let's take the following vector x
.
x <- c(50.333, 195.333, 186, 214.333, 246.667)
Decimal numbers x
will always be zero, 1/3, or 2/3 (i.e. 0.0, 0.333, or 0.667). I would like to quickly change their corresponding decimal places to the result of the following
> round(x %% 1/3, 1)
[1] 0.1 0.1 0.0 0.1 0.2
means that for x
- if 0 is decimal it is still zero
- if 0.333 is decimal it changes by 0.1
- if 0.667 is decimal, it changes by 0.2
Currently I am clunkily converting to character and then reverting back to numeric to get the next desired result ...
> as.numeric(paste0(round(x, 0), sub("0", "", round(x %% 1/3, 1))))
[1] 50.1 195.1 186.0 214.1 247.2
Is there a mathematical way to do this without forcing the character?
source to share
Why not just get the fraction for each number and divide it by .333 (round up), then divide by 10 to get the converted number you want. Mathematically:
- intpart = floor (number);
- fracpart = number -intpart
- newfracpart = (fracpart / .333)
- new number = intpart + newfracpart / 10.0
I'm not sure why you want to encode your numbers this way ... any specific reason?
You might want to change the number to "number of thirds" and use modulo 3 to get the fractional part and number / 3 for int
source to share