我正在尝试使用R中的sf包创建一个95%最小凸多边形。只要我只对一个变量分组,我的代码就能正常工作,但是当我对两个变量进行分组时,输出会失去其sf类并变成grouped_df。
这个代码可以输出我想要的结果。但是当我尝试按两个变量进行分组时,结果会丢失sf类。
这里是一个玩具数据集作为示例:
library(dplyr)
set.seed(12)
toy <- tibble::tibble(
ID = rep(c(1,2), each = 10),
year = rep(c(1,2), 10),
lat = runif(20, 1, 10),
long = runif(20, 1, 10)
) %>%
sf::st_as_sf(., coords = c("long", "lat"))
toy %>%
group_by(ID) %>%
summarize(.groups = "keep") %>%
mutate(cent = sf::st_centroid(geometry)) %>%
sf::st_cast(to = "POINT") %>%
mutate(dist = sf::st_distance(geometry, cent, by_element = TRUE)) %>%
filter(dist <= quantile(dist, .95)) %>%
summarize() %>%
sf::st_convex_hull() %>%
class()
这个代码可以输出我想要的结果。但是当我尝试按两个变量进行分组时,结果会丢失sf类。
toy %>%
group_by(ID, year) %>%
summarize(.groups = "keep") %>%
mutate(cent = sf::st_centroid(geometry)) %>%
sf::st_cast(to = "POINT") %>%
mutate(dist = sf::st_distance(geometry, cent, by_element = TRUE)) %>%
filter(dist <= quantile(dist, .95)) %>%
summarize() %>%
sf::st_convex_hull() %>%
class
我的代码中是否有什么问题导致我无法按两个变量进行分组?