![](/img/trans.png)
[英]R data.table sorting by group with "other" at bottom of each group
[英]Determine which points are farthest from each other set of coordinates in data.table R
我有这样的数据:
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)))
这有帮助吗?
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行相距最远。
不使用data.table
或geosphere
,但在这里是一个sf
的替代方案,示出了查找与给定的密集矩阵右距离st_distance
。 在这里您可以看到:
set.seed
因此您应该能够重现此内容 st_as_sf
和适当的crs
将坐标列转换为sf
点 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)
由reprex软件包 (v0.2.0)于2018-07-25创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.