r - 如果 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))
解决方案
这是一种更新Latitude
列test
以重现 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
推荐阅读
- jquery - 如何在 laravel 中使用 ajax 上传文件?
- java - Android studio 如何从 CalendarView 获取 int 值(年、月、日)并使用它保存在 SQLite 中
- android - 无法在 mac OS 中启动 ADB
- docusignapi - DocuSign:“直播”,现在我收到 404 错误
- c++ - 如何读取 png 中的 IHDR 值?
- r - Spark Dataframe 到 R Dataframe 异常期间的 KryoSerializer 异常
- freeswitch - 在 Freeswitch 中将多个输入语音拆分为多文件记录
- sql - 如何使用 knex 迁移更改 postgresql 数据库中列的数据类型?
- javascript - 如何在 GAS 中将原始值转换为日期对象
- dart - Flutter 将 Hive 数据库与 Riverpod 集成