计算R中的栅格堆栈中的点数

时间:2019-07-25 14:40:42

标签: r raster r-raster

我想计算栅格堆栈中的点数,包括零。为此,我做了:

#Packages
library(raster)
library(sp)
library(rgdal)

## Create a simulated RBG rasters
r <- raster(nc=30, nr=30)
r <- setValues(r, round(runif(ncell(r))* 255))
g <- raster(nc=30, nr=30)
g <- setValues(r, round(runif(ncell(r))* 255))
b <- raster(nc=30, nr=30)
b <- setValues(r, round(runif(ncell(r))* 255))
rgb<-stack(r,g,b)
plotRGB(rgb,
        r = 1, g = 2, b = 3)

##Given interesting points coordinates
xd     <- c(-24.99270,45.12069,99.40321,73.64419)
yd  <- c(-45.435267,-88.369745,-7.086949,44.174530)
pts <- data.frame(xd,yd)
pts_s<- SpatialPoints(pts)
points(pts_s, col="black", pch=16)

#Count number of points inside each raster
res<-NULL
for(i in 1:3){
  pointcount = function(r, pts){
  # make a raster of zeroes like the input
  r2 = r
  r2[] = 0
  # get the cell index for each point and make a table:
  counts = table(cellFromXY(r,pts))
  # fill in the raster with the counts from the cell index:
  r2[as.numeric(names(counts))] = counts
  return(r2)
 }
r2 = pointcount(rgb[[i]], pts_s)
res<-rbind(res,c(r2))
}
#

> res
     [,1]
[1,] ?   
[2,] ?   
[3,] ? 

我的功能不起作用。我将在res输出中看到4、4和4。请问,关于我的股票错误有什么想法吗?在此先感谢!

2 个答案:

答案 0 :(得分:1)

不清楚计算“栅格中的点”是什么意思。但是下面是一些建议。这是R-当您开始为此类问题编写循环时,几乎可以肯定,您会忽略一种更直接的方法

示例数据

r <- raster(nc=30, nr=30)
values(r) <- 1:ncell(r)
s <- stack(r, r*2)
# 5 points, 1 outside raster
xd  <- c(-24,45,99,73,200)
yd  <- c(-45,-88,-7,44,100)
pts <- cbind(xd,yd)

您想知道这些点是否与栅格相交?那你可以做

 sum(!is.na(cellFromXY(r, pts)))
 #[1] 4

 length(intersect(SpatialPoints(pts), r))
 #[1] 4

我想您不希望这样做,因为对于RasterStack中的所有层,答案都是相同的(并且您可以使用rs

还是您想知道哪些点位于不是NA的单元格上?

e <- extract(s, pts)
colSums(!is.na(e))
#layer.1 layer.2 
#      4       4 

还是计算每个像元的点数?

rp <- rasterize(pts, r, fun="count")
freq(rp)
#     value count
#[1,]     1     4
#[2,]    NA   896

答案 1 :(得分:0)

为您的循环添加了一些修复程序:(1)作为长度为3的整数向量预先分配了res; (2)使pointcount返回计数总和,这就是您要说的; (3)用每次迭代的求和结果填充res

res<-rep(NA_integer_, 3) #pre-allocates the result vector that will be filled in the loop
for(i in 1:3){
  pointcount = function(r, pts){
    # make a raster of zeroes like the input
    #r2 = r #not necessary
    #r2[] = 0 #not necessary
    # get the cell index for each point and make a table:
    counts = table(cellFromXY(r,pts))
    # fill in the raster with the counts from the cell index
    #r2[as.numeric(names(counts))] = counts #don't need this
    #return(r2) #don't need this
    sum(counts) #return the sum of counts; 'return' is implied so not necessary code
  }
  result = pointcount(rgb[[i]], pts_s)
  #res<-rbind(res,c(r2)) #not functional: r2 is a raster, so rbind does not make sense
  res[i] = result #fill the correct slot of res with result (i.e. sum of counts)
}