使用R中的矢量多边形提取光栅像素值

使用R中的矢量多边形提取光栅像素值,r,gis,raster,R,Gis,Raster,我已经为此挣扎了几个小时。 我有一个形状文件(称为“shp”),包含177个多边形,即177个县。此形状文件覆盖在光栅上。我的光栅(称为“ras”)由具有不同污染值的像素组成 现在我想提取每个多边形的所有像素值及其出现次数 这正是QGIS功能“分区直方图”所做的。但我想在R做同样的事情 我尝试了extract()函数,并获得了每个县的平均值,这已经是第一步了,但我想做一个像素分布(直方图) 有人能帮我一下吗 非常感谢, Marie Laure请始终提供一个最小的、独立的、可复制的示例。这使得回答

我已经为此挣扎了几个小时。 我有一个形状文件(称为“shp”),包含177个多边形,即177个县。此形状文件覆盖在光栅上。我的光栅(称为“ras”)由具有不同污染值的像素组成

现在我想提取每个多边形的所有像素值及其出现次数

这正是QGIS功能“分区直方图”所做的。但我想在R做同样的事情

我尝试了extract()函数,并获得了每个县的平均值,这已经是第一步了,但我想做一个像素分布(直方图)

有人能帮我一下吗

非常感谢,


Marie Laure

请始终提供一个最小的、独立的、可复制的示例。这使得回答起来很容易,其他人也很容易从中学习。而且,在大多数情况下,举这样一个例子可以让你回答自己的问题。这里有一个(几乎是字面上的?raster::extract,所以不难制作)

库(光栅)

非常感谢你的帮助。下一次我保证我会小心,更详细地解释我的问题

在你的帮助下,我设法找到了解决办法。 我还使用了这个网站:

作为参考,首先我必须卸载“tidyr”包,因为它与extract函数有冲突

如果它可以帮助某人,以下是最终代码:

# Libraries loading
library(raster) 
library(rgdal)
library(sp)

# raster layer import
ras=raster("C:/*.tif")

# shapefile layer import
shp<-shapefile("C:/*.shp")

# Extract the values of the pixels raster per county
ext <- extract(ras, shp, method='simple')

# Function to tabulate pixel values by region & return a data frame
tabFunc                            <- function(indx, extracted, region, regname) {
  dat                              <- as.data.frame(table(extracted[[indx]]))
  dat$name                         <- region[[regname]][[indx]]
  return(dat)
}

# run through each county & compute a table of the number
# of raster cells by pixel value. ("CODE" is the county code) 
tabs <- lapply(seq(ext), tabFunc, ext, shp, "CODE")

# assemble into one data frame
df <- do.call(rbind, tabs)  

# to see the data frame in R
print(df)

# table export 
write.csv(df,"C:/*.csv", row.names = FALSE)
#库加载
图书馆(光栅)
图书馆(rgdal)
图书馆(sp)
#光栅图层导入
ras=光栅(“C:/*.tif”)
#形状文件图层导入
小水电
v <- extract(r, polys)
par(mfrow=c(1,2))
z <- lapply(v, hist)
mains <- c("first", "second")
par(mfrow=c(1,2))
z <- lapply(1:length(v), function(i) hist(v[[i]], main=mains[i]))
z <- lapply(1:length(v), function(i) barplot(table(v[[i]]), main=mains[i]))
# Libraries loading
library(raster) 
library(rgdal)
library(sp)

# raster layer import
ras=raster("C:/*.tif")

# shapefile layer import
shp<-shapefile("C:/*.shp")

# Extract the values of the pixels raster per county
ext <- extract(ras, shp, method='simple')

# Function to tabulate pixel values by region & return a data frame
tabFunc                            <- function(indx, extracted, region, regname) {
  dat                              <- as.data.frame(table(extracted[[indx]]))
  dat$name                         <- region[[regname]][[indx]]
  return(dat)
}

# run through each county & compute a table of the number
# of raster cells by pixel value. ("CODE" is the county code) 
tabs <- lapply(seq(ext), tabFunc, ext, shp, "CODE")

# assemble into one data frame
df <- do.call(rbind, tabs)  

# to see the data frame in R
print(df)

# table export 
write.csv(df,"C:/*.csv", row.names = FALSE)