[英]r - lapply divides a column by an integer value from different dataset, unexpected result
[英]Extract the Correct Column from the Result of lapply in R
我有一個測深柵格和一個邊界網格化的 shapefile。
我無法隔離 lapply 生成的列表的“值”列。
目的是使用柵格平均值列作為 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 列表 object 中的整個第三列,但 [[3]] 只提供第三行
如何從 Mean_Raster_Values 訪問第三列?
我們可能需要將列表unlist
list
為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
,它會返回一個向量,默認情況下simplify = TRUE
in sapply
因此我們可以直接創建列
GridShapefile$Raster_Values <- sapply(Raster_Values, FUN=mean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.