从spatialpolygonsdataframe中提取栅格堆栈中的值

时间:2013-02-04 08:05:09

标签: r geospatial polygon raster

我有一个栅格堆栈,里面有27个栅格。我在空间多边形数据框中有27个相应的多边形。我想将多边形[i]覆盖在栅格[i]上,从栅格[i]中提取和求和,得到多边形[i]中的单元格数,然后将和值除以#细胞换句话说,栅格是利用率分布或核心使用密度。我想知道在多边形区域中发生了很多用途,它与栅格重叠。我想除以多边形中的单元格数来考虑多边形的大小。

我有一个脚本给我这样做,只是为了从数据框中的任意数量的空间多边形中提取1个栅格中的数据。它工作,它的丑陋,我现在想将它转换为更流线的东西。我只希望我周围有人可以提供帮助,因为这可能需要一段时间?

这是我已经给出的代码以及我对我的想法的总结:

msum99Kern07 = SpatialPolygonDataFrame (many polygons)
KERNWolfPIX07m = Raster (this is a single raster, I have 27 rasters I put into a stack

#Extracting value from raster to many polygons 
sRISK_Moose07m<- extract(KERNWolfPIX07m, msum99Kern07,df=FALSE,method='bilinear')

#Calculate THE SUM FOR EACH polygon#
sRISK_Moose07m<-unlist(lapply(sRISK_Moose07m, function(x) if (!is.null(x)) sum(x, na.rm=TRUE) else NA ))
sRISK_Moose07m<-as.data.frame(sRISK_Moose07m)

#Im not sure why these next commands are needed Im only guessing
#data.frame(levels) as there are many polygons creating a dataframe to put the info into
ID_SUM_07<-as.data.frame(levels(as.factor(msum07locs$ID2)))
#ADD ID TO THE risk data frame 
sRISK_Moose07m$ID<-ID_SUM_07[,1] 

#NUMBER OF CELLS WITHIN POLYGON EXTRACT CELLS/ POLYGON
NB_SUM2007m<-cellFromPolygon(KERNWolfPIX07m, msum99Kern07)
NB_SUM07m<-unlist(lapply(NB_SUM2007m, function(x) if (!is.null(x)) length(x) else NA ))

#####CONVERT TO DATA FRAME
NB_SUM07m<-as.data.frame(NB_SUM07m)

###ADD THE NB OF CELLS TO THE RISK_SUM FILE###
sRISK_Moose07m$NB_CELLS<-NB_SUM07m[,1]

###DIVIDING VALUE by NB CELLS##
sRISK_Moose07m$DIVID<-sRISK_Moose07m$sRISK_Moose07m/sRISK_Moose07m$NB_CELLS 

现在,我的空间多边形数据框有27个多边形,而我的光栅堆栈有27个栅格。我想选择栅格[i]和polygon [i]并提取,求和,并计算重叠区域的核密度。需要注意的一点是,我可能会收到一个错误,因为多边形和栅格可能没有重叠......我根本不知道如何在R中检查这个。

我的剧本已经开始了:

moose99kern = spatial polygon data frame 27 moose
Rastwtrial = stack of 27 rasters having the same unique name as the ID in moose99kern

mkernID=unique(moose99kern$id)

for (i in length(mkernID)){
           r = Rastwtrial[Rastwtrial[[i]]== mkernID[i]] #pick frm Rasterstack the raster that has the same name
            mp = moose99kern[moose99kern$id == mkernID[i]] #pick from spatialpolygondataframe the polygon that has the same name 

            RISK_MooseTrial<- extract(r, mp, df=T, method'bilinear')
            risksum = (RISK_MooseTrial, function(x) if (!is.null(x)) sum(x, na.rm=TRUE) else NA )#sum all the values that were extracted from the raster

我的脚本甚至没有开始工作,因为我不知道如何索引栅格堆栈。但即使如此,一次只能通过1个栅格/ 1个多边形,我不知道在代码中下一步该做什么。如果这对StackOverflow来说太多了,我道歉。我只是严重陷入困境,无处可转。
这是多边形的2个人的测试数据

 dput(mtestpoly) 
    new("SpatialPolygonsDataFrame"
        , data = structure(list(id = structure(1:2, .Label = c("F01001_1", "F07002_1"
    ), class = "factor"), area = c(1259.93082578125, 966.364499511719
    )), .Names = c("id", "area"), row.names = c("F01001_1", "F07002_1"
    ), class = "data.frame")
        , polygons = list(<S4 object of class structure("Polygons", package = "sp")>, 
        <S4 object of class structure("Polygons", package = "sp")>)
        , plotOrder = 1:2
        , bbox = structure(c(6619693.77161797, 1480549.31292137, 6625570.48348294, 
    1485861.5586371), .Dim = c(2L, 2L), .Dimnames = list(c("x", "y"
    ), c("min", "max")))
        , proj4string = new("CRS"
        , projargs = NA_character_

dput(Rastwtest)

new("RasterStack"
    , filename = ""
    , layers = list(<S4 object of class structure("RasterLayer", package = "raster")>, 
    <S4 object of class structure("RasterLayer", package = "raster")>)
    , title = character(0)
    , extent = new("Extent"
    , xmin = 1452505.6959799
    , xmax = 1515444.7110552
    , ymin = 6575235.1959799
    , ymax = 6646756.8040201
)
    , rotated = FALSE
    , rotation = new(".Rotation"
    , geotrans = numeric(0)
    , transfun = function () 
NULL
)
    , ncols = 176L
    , nrows = 200L
    , crs = new("CRS"
    , projargs = NA_character_
)
    , z = list()
    , layernames = "Do not use the layernames slot (it is obsolete and will be removed)\nUse function 'names'"
)

2 个答案:

答案 0 :(得分:6)

也许我想念一些东西,但我认为你过分复杂了这个问题。对我来说,你有:

  1. 栅格堆栈:栅格列表:ss
  2. 与ss:polys
  3. 大小相同的多边形列表

    您需要为(ss,polys)每对(图层,多边形)应用extract

    sapply(1:nlayers(ss), function(i) {
         m <- extract(ss[[i]],polys[i], method='bilinear', na.rm= T)[[1]]
         d <- ifelse (!is.null(m) , sum(m)/length(m), NA)
         d
    })
    

    这里有2个legnths的例子,因为你没有给出一个可重复的例子:

    ## generate some data
    library(raster)
    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))
    ## In your case you need something like SpatialPolygons(moose99kern)
    polys <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), 
                                  Polygons(list(Polygon(cds2)), 2)))
    r   <- raster(ncol=36, nrow=18)
    r[] <- 1:ncell(r)
    r1   <- raster(ncol=36, nrow=18)
    r1[] <- seq(-1,-2,length.out=ncell(r1))
    ss <- stack(r,r1)
    ## density compute
    sapply(1:nlayers(ss), function(i) {
             ## sum of values of the cells of a Raster ss[[i]] covered by the poly polys[i]
             m <- extract(ss[[i]],polys[i], method='bilinear', na.rm= T)[[1]]
             d <- ifelse (!is.null(m) , sum(m)/length(m), NA)
    
    })
    
    [1] 387.815789  -1.494714
    

答案 1 :(得分:3)

当您询问有关R的问题时,请始终使用简单的可重复示例,而不是您自己的数据;除非您想要做的事情适用于这样的示例,但不适用于您的数据,但仍然显示可行的示例和您获得的错误消息。您通常可以从帮助文件中的示例开始,如下面的?extract

r <- raster(ncol=36, nrow=18)
r[] <- 1:ncell(r)
s <- stack(r, r*2)
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 <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), 
                         Polygons(list(Polygon(cds2)), 2)))

v <- extract(s, polys, small=TRUE)

#cellnumbers for each polygon
sapply(v, NROW)

# mean for each polygon
sapply(v, function(x) apply(x, 2, mean, na.rm=T))

如果你的一些polgyons我们在光栅之外(即返回NULL,但是“small = TRUE”选项应该避免栅格内部非常小的多边形问题),需要改进sapply中的函数。还要注意有使用SpatialPolygon *对象进行提取时没有“method”参数。

不要使用循环,除非为每个多边形都有很多单元格来防止内存问题。