You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:如何从lapply结果中提取正确列并赋值给Shapefile?

解决方案

首先明确:Mean_Raster_Values是通过lapply生成的单元素列表,每个列表项对应一个网格的栅格均值,不存在“第三列”的结构。你需要的是把列表中的所有均值提取为一个向量,再赋值给Shapefile的新列。

修正后的完整代码

library("sf")
library("raster")

# 下载栅格数据
download.file("https://transfer.sh/T8BJjo/Raster.tif", destfile = "Raster.tif", method = "curl")
Raster_Data <- raster("Raster.tif")

# 修正:原文件是gpkg格式,不要存成tif
download.file("https://transfer.sh/FgqHhS/HexGridShapefile.gpkg", destfile = "HexGridShapefile.gpkg", method = "curl")
GridShapefile <- st_read("HexGridShapefile.gpkg")

# 提取每个网格内的栅格值
Raster_Values <- extract(Raster_Data, GridShapefile)

# 方法1:用sapply直接生成均值向量(比lapply更适合这种场景)
Mean_Raster_Values <- sapply(Raster_Values, FUN=mean, na.rm=TRUE) # 建议加na.rm处理缺失值

# 方法2:如果已经用了lapply,把列表转成向量
# Mean_Raster_Values <- unlist(lapply(Raster_Values, FUN=mean, na.rm=TRUE))

# 将均值向量赋值给Shapefile的新列
GridShapefile$Raster_Mean <- Mean_Raster_Values

关键说明

  • 修正了Shapefile下载时的格式错误:原文件是GeoPackage(.gpkg),之前存成.tif会导致st_read读取失败。
  • sapply会直接返回一个与网格数量匹配的数值向量,不需要额外转换;如果用lapply,则通过unlist()将列表转为向量。
  • 建议添加na.rm=TRUE参数,避免栅格中存在缺失值时均值计算返回NA。

内容的提问来源于stack exchange,提问作者Grant Rogers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 02:00:34