首页 > 解决方案 > 如果 2 列数据在其上方的行中具有相同的值,则向其添加 0.00001

问题描述

我有一个数据框,其中包含纬度列和经度列,如下所示

test <- data.frame("Latitude" = c(45.14565, 45.14565, 45.14565, 45.14565, 33.2222, 
31.22122, 31.22122), "Longitude" = c(-105.6666, -105.6666, -105.6666, -104.3333, 
-104.3333, -105.77777, -105.77777))

我想让每个值都精确到小数点后 5 位,并检查纬度和经度对是否与其上方的对相同,将 0.00001 添加到纬度和经度值。所以我的数据会变成这样:

test_updated <- data.frame("Latitude" = c(45.14565, 45.14566, 45.14567, 45.14565, 
33.22220, 31.22122, 31.22123), "Longitude" = c(-105.66660, -105.66661, -105.66662, 
-104.33330, -104.33330, -105.77777, -105.77778))

标签: rloopsdecimal

解决方案


这是一种更新Latitudetest以重现 OP 的预期结果的方法:

options(digits = 8) # required to print all significant digits of Longitude
library(data.table)
setDT(test)[, `:=`(Latitude  = Latitude  + (seq(.N) - 1) * 0.00001,
                   Longitude = Longitude + (seq(.N) - 1) * 0.00001), 
            by = .(Latitude, Longitude)]
test
   Latitude  Longitude
1: 45.14565 -105.66660
2: 45.14566 -105.66659
3: 45.14567 -105.66658
4: 45.14565 -104.33330
5: 33.22220 -104.33330
6: 31.22122 -105.77777
7: 31.22123 -105.77776

为了比较

test_updated
  Latitude  Longitude
1 45.14565 -105.66660
2 45.14566 -105.66661
3 45.14567 -105.66662
4 45.14565 -104.33330
5 33.22220 -104.33330
6 31.22122 -105.77777
7 31.22123 -105.77778

差异是由于 OP 要求将 0.00001 添加到纬度和经度值以及 OP 的预期结果,其中 0.00001已从经度值中减去。

编辑

为了重现预期结果,必须考虑值的符号。不幸的是,基本 Rsign()函数返回零sign(0)。所以,我们fifelse(x < 0, -1, 1)改用。

此外,我们可以借鉴Henrik 的绝妙想法来使用该rowid()函数来避免分组。

options(digits = 8) # required to print all significant digits of Longitude
library(data.table)
cols <- c("Latitude", "Longitude")
setDT(test)[, (cols) := lapply(.SD, \(x) x + fifelse(x < 0, -1, 1) * 
                                 (rowidv(.SD, cols) - 1) * 0.00001), .SDcols = cols]
test
   Latitude  Longitude
1: 45.14565 -105.66660
2: 45.14566 -105.66661
3: 45.14567 -105.66662
4: 45.14565 -104.33330
5: 33.22220 -104.33330
6: 31.22122 -105.77777
7: 31.22123 -105.77778

推荐阅读