合并两个POINT几何列生成list列而非POINT列的解决方法
解决sf几何列合并生成list列的问题
问题背景
在处理两个包含POINT几何列的tibble时,尝试通过ifelse(st_is_empty(geom1), geom2, geom1)实现类似coalesce()的逻辑(优先使用geom1,空值时 fallback 到geom2),但结果生成的geom3是list列,而非预期的POINT几何列。
解决方案
方法1:用case_when()替代ifelse()
ifelse()会自动简化输出类型,将sf几何对象拆解为列表;而dplyr::case_when()可以保留sf几何列的原生类型,直接得到POINT列:
library(dplyr, warn.conflicts = FALSE) library(sf) # 构造原始数据 df1 <- tibble(x = c("a", "b"), lat = c(0, NA), lon = c(0, NA)) |> st_as_sf(coords = c("lon", "lat"), na.fail = FALSE, sf_column_name = "geom1", crs = 4326) |> as_tibble() df2 <- tibble(x = c("a", "b"), lat = c(1, 2), lon = c(3, 4)) |> st_as_sf(coords = c("lon", "lat"), na.fail = FALSE, sf_column_name = "geom2", crs = 4326) |> as_tibble() # 使用case_when实现合并逻辑 df_combined <- df1 |> left_join(df2, join_by(x)) |> mutate( geom3 = case_when( st_is_empty(geom1) ~ geom2, TRUE ~ geom1 ) ) # 查看结果 df_combined
输出结果:
#> # A tibble: 2 × 4 #> x geom1 geom2 geom3 #> <chr> <POINT [°]> <POINT [°]> <POINT [°]> #> 1 a (0 0) (3 1) (0 0) #> 2 b EMPTY (4 2) (4 2)
方法2:将已生成的list列转换为POINT几何列
如果已经得到了list类型的geom3,可以通过st_sfc()将列表转换为sf几何集合(sfc对象),并指定CRS来恢复POINT列:
# 假设df中已经有list类型的geom3列 df_fixed <- df_with_list_geom |> mutate( geom3 = st_sfc(geom3, crs = 4326) ) df_fixed
来源说明
内容的提问来源于stack exchange,提问作者bretauv
相关产品推荐
相关产品推荐

