[英]Calculate the average of a cloud of points based on a grouping variable with sf in R
我有很多點要計算每個分組變量的平均值:
x = st_sfc(st_polygon(list(rbind(c(0,0),c(90,0),c(90,90),c(0,90),c(0,0)))), crs = st_crs(4326))
plot(x, axes = TRUE, graticule = TRUE)
plot(p <- st_sample(x, 7), add = TRUE)
p=st_as_sf(p)
p$test=c("A","A","B","C","C","D","D")
當使用dplyr
時,像這樣,我得到一個 NA。
p %>%
group_by(test) %>%
summarize(geometry = mean(geometry))
我只想要幾何的平均值,而不是 1 點,也不是多點。
不確定完全理解您在尋找什么,但我正在嘗試一下!
因此,請使用sf
和dplyr
庫在下面找到一種可能的解決方案。 我猜你正在尋找aggregate()
function 而不是group_by()
代表
library(sf)
library(dplyr)
R1 <- p %>% aggregate(.,
by = list(.$test),
function(x) x = x[1]) %>%
st_centroid() %>%
select(-Group.1)
#> Warning in st_centroid.sf(.): st_centroid assumes attributes are constant over
#> geometries of x
R1
#> Simple feature collection with 4 features and 1 field
#> Attribute-geometry relationship: 0 constant, 1 aggregate, 0 identity
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 2.7875 ymin: 12.91954 xmax: 59.60413 ymax: 51.81421
#> Geodetic CRS: WGS 84
#> test geometry
#> 1 A POINT (27.17167 12.91954)
#> 2 B POINT (2.7875 22.54184)
#> 3 C POINT (59.60413 46.90029)
#> 4 D POINT (56.34763 51.81421)
R2 <- R1 %>%
st_coordinates() %>%
cbind(st_drop_geometry(R1),.)
R2
#> test X Y
#> 1 A 27.17167 12.91954
#> 2 B 2.78750 22.54184
#> 3 C 59.60413 46.90029
#> 4 D 56.34763 51.81421
plot(x)
plot(p, add = TRUE)
plot(R1, pch = 15, add = TRUE)
點是您的數據,小方塊是每組的質心(僅供參考,出於可重復性目的,我將種子設置為427
)
sf_use_s2(FALSE)
。 為了向您展示差異,這里是使用sf_use_s2(FALSE)
的結果(在這種情況下,您可以看到,對於每個組,質心正好位於連接兩個點的線上;您可以根據根據您的需要)由代表 package (v2.0.1) 於 2022 年 1 月 3 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.