在R中用lapply处理嵌套列表的if/else逻辑提取POINT要素
解决方案
先构造一个可复现的示例嵌套列表(模拟你的nums结构):
library(sf) # 模拟sf生成的嵌套列表nums nums <- list( # GEOMETRYCOLLECTION:包含其他几何+POINT st_geometrycollection(list(st_point(c(1,2)), st_point(c(3,4)))), # MULTIPOINT:包含1个或多个点 st_multipoint(rbind(c(5,6), c(7,8))), st_geometrycollection(list(st_linestring(rbind(c(9,10), c(11,12))), st_point(c(13,14)))), st_multipoint(rbind(c(15,16))) )
步骤1:编写自定义提取函数
针对两种几何类型分别处理,输出单条坐标数据:
extract_point <- function(geom) { # 判断几何类型 geom_type <- st_geometry_type(geom) if (geom_type == "GEOMETRYCOLLECTION") { # 提取第二个子要素(POINT) target_point <- geom[[2]] } else if (geom_type == "MULTIPOINT") { # 将MULTIPOINT转为单个POINT(这里取第一个点,需调整逻辑可修改) coords_matrix <- st_coordinates(geom) target_point <- st_point(coords_matrix[1, ]) } else { # 非目标类型返回NA行 return(data.frame(Long = NA, Lat = NA)) } # 提取坐标转为数据框行 coords <- st_coordinates(target_point) data.frame(Long = coords[1], Lat = coords[2]) }
步骤2:批量处理并合并结果
用lapply遍历所有元素,再合并为长格式DataFrame:
# 批量处理每个几何要素 processed_list <- lapply(nums, extract_point) # 合并为最终数据框 final_df <- do.call(rbind, processed_list)
运行后final_df的输出结果:
Long Lat 1 3 4 2 5 6 3 13 14 4 15 16
注意事项
- 如果你的MULTIPOINT需要取所有点的平均坐标而非第一个,可将
coords_matrix[1, ]替换为colMeans(coords_matrix) - 若有其他几何类型混入,可在函数中添加对应的判断逻辑
内容的提问来源于stack exchange,提问作者simpson
相关产品推荐
相关产品推荐

