从r中lapply的结果中提取正确的列



我有一个测深光栅和一个边界网格形状文件。

我无法隔离lapply生成的列表中的'values'列。

目的是使用栅格平均值列作为shapefile

中的新列。
library("sf")
library("raster")
download.file("https://transfer.sh/T8BJjo/Raster.tif", destfile = "Raster.tif", method = "curl")
Raster_Data <- raster("Raster.tif")
download.file("https://transfer.sh/FgqHhS/HexGridShapefile.gpkg", destfile = "HexGridShapfile.tif", method = "curl")
GridShapefile <- st_read("HexGridShapfile.tif")
Raster_Values <- extract(Raster_Data, GridShapefile)
Mean_Raster_Values <- lapply(Raster_Values, FUN=mean)
#Extract Mean Values and set them to Column of Shapefile
GridShapefile$Raster_Values <- Mean_Raster_Values[[3]]  # INCORRECT IMPLEMENTATION

最后一行应该从Mean_Raster_Values列表对象分配整个第三列,但[[3]]只提供第三行

如何从Mean_Raster_Values访问第三列?

我们可能需要将unlistlist转换为vector,因为每个列表元素都是数字并且是单个值(mean返回单个数字输出)

GridShapefile$Raster_Values <- unlist(Mean_Raster_Values)

与产出

> head(GridShapefile)
Simple feature collection with 6 features and 1 field
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 1.276447 ymin: 39.20347 xmax: 1.351447 ymax: 39.47771
Geodetic CRS:  WGS 84
geom Raster_Values
1 POLYGON ((1.301447 39.24677...     -691.8400
2 POLYGON ((1.301447 39.33337...     -967.5200
3 POLYGON ((1.301447 39.41997...    -1357.5200
4 POLYGON ((1.326447 39.20347...     -588.7440
5 POLYGON ((1.326447 39.29007...     -811.5081
6 POLYGON ((1.326447 39.37667...    -1156.5040

如果我们使用sapply而不是lapply,它将返回一个向量,默认情况下,sapply中的simplify = TRUE,因此我们可以直接创建列

GridShapefile$Raster_Values <- sapply(Raster_Values, FUN=mean)

最新更新