Phil Phil - 3 months ago 27
R Question

How to round to 0.25 or 0.75, but not 0.00 or 0.50 in R?

I'm using R and I want to round my data to the nearest 0.25 or 0.75, but not including 0.00 or 0.50.

For example, if I wanted to round to the nearest 0.00 or 0.50, I would do as follows:

test <- seq(1,10,0.33)
[1] 1.00 1.33 1.66 1.99 2.32 2.65 2.98 3.31 3.64 3.97 4.30 4.63 4.96 5.29 5.62 5.95 6.28 6.61 6.94 7.27 7.60 7.93 8.26 8.59 8.92 9.25 9.58 9.91


Round to 0.00 or 0.50:

round(test * 2)/2
[1] 1.0 1.5 1.5 2.0 2.5 2.5 3.0 3.5 3.5 4.0 4.5 4.5 5.0 5.5 5.5 6.0 6.5 6.5 7.0 7.5 7.5 8.0 8.5 8.5 9.0 9.0 9.5 10.0


I could do the same for multiples of 0.25. What could I do to round these numbers to 0.25 or 0.75 exclusively, excluding 0.50 and 0.00?

Answer

How about round((test + 0.25) * 2) / 2 - 0.25? For your test, it gives:

# [1] 0.75 1.25 1.75 1.75 2.25 2.75 2.75 3.25 3.75 3.75 4.25 4.75 4.75 5.25 5.75
#[16] 5.75 6.25 6.75 6.75 7.25 7.75 7.75 8.25 8.75 8.75 9.25 9.75 9.75

You may also do round((test - 0.25) * 2) / 2 + 0.25, giving

# [1] 1.25 1.25 1.75 1.75 2.25 2.75 2.75 3.25 3.75 3.75 4.25 4.75 4.75 5.25 5.75
#[16] 5.75 6.25 6.75 6.75 7.25 7.75 7.75 8.25 8.75 8.75 9.25 9.75 9.75

The behaviour differs at the round-off direction for whole number. Take 1 as an example. In the first case, it is rounded down to 0.75, while in the second case, it is rounded up to 1.25. Whole number is a "grey area" here; you need decide what direction you want.