我有这样的数据:
library(data.table)
dtorig <- data.table(x=1:100,lat=(sample(c(800:900),100))/100, lon=(sample(c(3800:3900),100))/100)
我想获得dtorig中彼此最远的行的位置。我的尝试(无效)如下:
###NOT WORK
library(geosphere)
extremep <- chull(dtorig[, c(3,2)])
extremepoints <- dtorig[extremep,]
wmax <- sapply(1:NROW(extremepoints), function(i) which.max(distm(extremepoints[i, c(3,2)],fun=distHaversine)))
答案 0 :(得分:1)
有帮助吗?
library(data.table)
library(geosphere)
dtorig <- data.table(x=1:100,lat=(sample(c(800:900),100))/100, lon=(sample(c(3800:3900),100))/100)
x <- distm(x = as.matrix(dtorig[, .(lon, lat)]), fun=distHaversine)
which(x == max(x), arr.ind = TRUE)
# row col
# [1,] 50 27
# [2,] 27 50
第27行和第50行相距最远。
答案 1 :(得分:1)
不使用data.table
或geosphere
,但是这里是sf
的替代方案,它说明了从st_distance
给出的密集矩阵中找到正确的距离。在这里您可以看到:
set.seed
,因此您应该能够重现此sf
和适当的st_as_sf
将坐标列转换为crs
点by_element = FALSE
中st_distance
的所有行之间的距离lower.tri
删除距离矩阵的重复下三角三角形gather
将矩阵的其余部分arrange(desc())
放入单个距离列中plot
中距离最远的点。library(tidyverse)
library(sf)
set.seed(12345)
dtorig <- tibble(
x = 1:100,
lat = (sample(c(800:900), 100)) / 100,
lon = (sample(c(3800:3900), 100)) / 100
)
sforig <- st_as_sf(dtorig, coords = c("lon", "lat"), crs = 4326)
distances <- sforig %>%
st_distance(by_element = FALSE) %>%
unclass %>%
`[<-`(lower.tri(., diag = TRUE), NA) %>%
as_tibble() %>%
rowid_to_column %>%
gather(colid, distance, starts_with("V"), na.rm = TRUE) %>%
arrange(desc(distance))
distances
#> # A tibble: 4,950 x 3
#> rowid colid distance
#> <int> <chr> <dbl>
#> 1 30 V68 138244.
#> 2 30 V75 137957.
#> 3 19 V30 135068.
#> 4 48 V78 131849.
#> 5 40 V90 131280.
#> 6 48 V90 130946.
#> 7 40 V78 130035.
#> 8 50 V68 128851.
#> 9 45 V48 128805.
#> 10 40 V45 128531.
#> # ... with 4,940 more rows
sforig %>%
st_geometry %>%
plot(col = "red", pch = 19)
sforig %>%
filter(x %in% c(30, 68)) %>%
st_geometry %>%
plot( add = TRUE, col = "blue", pch = 19)
上最远的一对点。setBackground
由reprex package(v0.2.0)于2018-07-25创建。