Here is an approach which updates the Latitude
column in test
to reproduce OP's expected result:
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
For comparison
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
The discrepancy is caused by OP's requirement to add 0.00001 to both the latitude and the longitude value and OP's expected result where
0.00001 have been subtracted from the negative longitude values.
Edit
In order to reproduce the expected result, the sign of the value has to be considered. Unfortunately the base R sign()
function returns zero for sign(0)
. So, we use fifelse(x < 0, -1, 1)
instead.
In addition, we can pick up Henrik's splendid idea to use the rowid()
function to avoid grouping.
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