gpt4 book ai didi

r - 计算数据框中多个纬度、经度点的中心点

转载 作者:行者123 更新时间:2023-12-05 09:07:01 25 4
gpt4 key购买 nike

我有一个看起来像这样的数据集:

site   lat      long 
bras2 41.21 -115.11
tex4 45.3 -112.31
bras2 41.15 -115.15
bras2 41.12 -115.19

对于具有相同 site 名称的样本,我想计算它们的中心点,然后将其作为列添加到数据集中。一些 site 名称重复两次,其他三次,其他四次。

像这样:

site   lat      long    centre_lat  centre_long 
bras2 41.21 -115.11 value here value here
tex4 45.3 -112.31 45.3 -112.31
bras2 41.15 -115.15 value here value here
bras2 41.12 -115.19 value here value here

我该怎么做?

最佳答案

如果您正在使用空间数据,您应该考虑使用 sf 包。它处理几何图形和函数以便在它们上很好地运行。

下面的代码显示了同时使用 sf::st_centroidgeosphere::centroid。我更喜欢 sf 的做事方式。

df <- read.table(header=TRUE, text= "site   lat      long 
bras2 41.21 -115.11
tex4 45.3 -112.31
bras2 41.15 -115.15
bras2 41.12 -115.19")


library(dplyr)
library(geosphere)
library(sf)

# Using sf's st_centroid
df_sf <- st_as_sf(df, coords = c('long', 'lat'))

centroids_sf <- df_sf %>%
group_by(site) %>%
summarize(geometry = st_union(geometry)) %>%
st_centroid


# Using geosphere::centroid
centroids_geoshpere <- df_sf %>%
group_by(site) %>%
filter(n() >2) %>% ## geosphere needs polygons therefore 3+ points
st_union() %>%
st_cast('POLYGON') %>%
as('Spatial') %>% # geoshpere expects SpatialPolygons objects
centroid()


centroids_geoshpere
#> [,1] [,2]
#> [1,] -115.15 41.16001
centroids_sf
#> Simple feature collection with 2 features and 1 field
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: -115.15 ymin: 41.16 xmax: -112.31 ymax: 45.3
#> CRS: NA
#> # A tibble: 2 x 2
#> site geometry
#> * <chr> <POINT>
#> 1 bras2 (-115.15 41.16)
#> 2 tex4 (-112.31 45.3)

看起来他们离同一点足够近了。我不认为 geosphere::centroid 可以为单个点提供质心,但可能是错误的。 sf::st_centroid 1,2, 或者更多的点都没有问题。reprex package 创建于 2020-12-20 (v0.3.0)

关于r - 计算数据框中多个纬度、经度点的中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65379274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com