舍入为特定值 r

问题描述 投票:0回答:1

我有一个坐标列表,需要以 0.1 的间隔进行舍入

使用

mutate(Long=round(Long/0.1)*0.1
就足够简单了(不确定这是否是最有效的,但它有效,但不是今天的问题。

问题是我需要舍入以匹配以下内容(所有长数以 0.04 结束,拉特以 0.03 结束)

例如 Lat 53.15 通常会向上舍入到 53.2,但我需要它向下舍入到 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 
r rounding
1个回答
0
投票

您可以移动数据,以便将其舍入为方便的值,然后取消移动。

round_offset = function(x, precision, offset) {
  round((x - offset) / precision) * precision + offset
}

下面的演示 - 我们可以看到所有

rounded
值都以 0.04 结尾,并且与原始值的差异都小于 0.05,因此它看起来工作正常。

## sample data
set.seed(47)
xx = seq(1, 2.5, by = 0.1) 
xx = xx + runif(length(xx), min = -.05, max = .05)

## use and checking
result = cbind(xx, rounded = round_offset(xx, precision = 0.1, offset = 0.04))
cbind(result, diff = result[, 2] - result[, 1])
#             xx rounded          diff
#  [1,] 1.047696    1.04 -0.0076961999
#  [2,] 1.087392    1.04 -0.0473916046
#  [3,] 1.226150    1.24  0.0138497970
#  [4,] 1.332249    1.34  0.0077508389
#  [5,] 1.407354    1.44  0.0326455583
#  [6,] 1.519141    1.54  0.0208587573
#  [7,] 1.588906    1.54 -0.0489061853
#  [8,] 1.696895    1.74  0.0431054025
#  [9,] 1.804331    1.84  0.0356690261
# [10,] 1.942489    1.94 -0.0024892050
# [11,] 1.963880    1.94 -0.0238797579
# [12,] 2.120199    2.14  0.0198012799
# [13,] 2.166219    2.14 -0.0262193643
# [14,] 2.309931    2.34  0.0300692983
# [15,] 2.400604    2.44  0.0393963890
# [16,] 2.540197    2.54 -0.0001973522
© www.soinside.com 2019 - 2024. All rights reserved.