我是R的新手,很难解决这个问题,因此请给予任何帮助. 我拥有每日洪水网格数据,用于计算某些位置周围的缓冲区中洪水的加权平均值.我在Q地理信息系统中清理了网格,并使用R通过以下行计算加权平均值:
library(sp)
library(raster)
library(ggplot2)
library(sf)
# Load the raster file into R
flooding_raster_data <- raster(raster_file)
# Print information or perform further processing as needed
print(paste("Loaded raster file:", raster_file))
# Extract values from the raster that fall within the buffer polygons
raster_values_in_buffer_weight <- extract(flooding_raster_data, buffer, fun = mean, na.rm = TRUE, weights=TRUE)
# Create a new buffer object with the extracted floodshare values
buffer_with_mean <- st_as_sf(buffer)
buffer_with_mean$floodshare <- raster_values_in_buffer_weight
# Write the sf object to a shapefile
st_write(buffer_with_mean, output_file_path, append = FALSE)
rm(flooding_raster_data, buffer_with_mean, raster_values_in_buffer_weight, raster_file)
我的问题是,对于没有数据(在Q地理信息系统中编码为无数据)的网格,缓冲区的加权平均值为0.我已经将其与Q地理信息系统中的分区平均值进行了判断,而这些相同的缓冲区在Q地理信息系统中的分区平均值为空.我很难弄清楚为什么R会发生这种情况,因为我认为R会导致平均NA或缺失,所以如果有人知道为什么,请告诉我以及我如何解决这个问题.再说一次,我完全是R初学者,所以我可能错过了一些非常明显的东西.
我试图使na.rm = RST,因为我认为问题可能出在R代码中处理NA值的方式上,但这只会使所有加权平均值为空,所以我想我不明白R如何处理丢失的数据.
EDIT
我go 判断了文档中的R extract,并 Select 了他们的示例代码,但将格栅值更改为NA,并且如果所有格栅值都是NA,它确实会将提取值的加权平均值为0作为多边形.为什么当其他所有内容都给出NA或NaN时,它没有给出NA作为加权平均值.我已在下面添加了复制代码.
###############################
# extract values with lines
###############################
r <- raster(ncol=36, nrow=18, vals=NA)
cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25))
cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55))
lines <- spLines(cds1, cds2)
extract(r, lines)
###############################
# extract values with polygons
###############################
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
polys <- spPolygons(cds1, cds2)
v <- extract(r, polys)
# mean for each polygon
mean_polyg <- unlist(lapply(v, function(x) if (!is.null(x)) mean(x, na.rm=TRUE) else NA ))
print(mean_polyg)
# weighted mean
v <- extract(r, polys, weights=TRUE, fun=mean, na.rm = TRUE)
print(v)