I have a list of co-ordinates that I need to round at 0.1 intervals
Easy enough with mutate(Long=round(Long/0.1)*0.1
(not sure if that's most efficient but it works and isn't the issue today.
The issue is I need to round to match the following (all Longs end in 0.04, Lats in 0.03)
For example Lat 53.15 would typically round UP to 53.2 but I need it to round down to 53.13
Long Lat
1 -3.24 53.13
2 -3.14 53.13
3 -3.04 53.13
4 -2.94 53.13
5 -2.84 53.13
6 -2.74 53.13
You can shift your data so that you can round it to a convenient value, then unshift it. (With credit to this answer for the round logic without the offset.)
round_offset = function(x, precision, offset) {
round((x - offset * sign(x)) / precision) * precision + offset * sign(x)
}
Demonstration below - we can see that all the rounded
values end in 0.04, and the difference from the original values are all less than 0.05, so it appears to be working correctly.
set.seed(47)
xx = seq(-0.3, 0.8, by = 0.1)
xx = xx + runif(length(xx), min = -.05, max = .05)
result = cbind(xx, rounded = round_offset(xx, precision = 0.1, offset = 0.04))
cbind(result, diff = result[, 2] - result[, 1])
# xx rounded diff
# [1,] -0.25230380 -0.24 0.012303800
# [2,] -0.21260840 -0.24 -0.027391605
# [3,] -0.07384980 -0.04 0.033849797
# [4,] 0.03224916 0.04 0.007750839
# [5,] 0.10735444 0.14 0.032645558
# [6,] 0.21914124 0.24 0.020858757
# [7,] 0.28890619 0.24 -0.048906185
# [8,] 0.39689460 0.44 0.043105403
# [9,] 0.50433097 0.54 0.035669026
# [10,] 0.64248920 0.64 -0.002489205
# [11,] 0.66387976 0.64 -0.023879758
# [12,] 0.82019872 0.84 0.019801280
Note that 0 will not be rounded as it's equidistant from both -0.04 and 0.04. If you want 0 to be rounded, I'd handle it as an exception after applying this algorithm. (Or perhaps by nudging the input just a little bit, if you add 1e-8
to your input 0
will be rounded up and nothing else is likely to be affected.)