【发布时间】:2023-04-04 13:08:01
【问题描述】:
我想计算栅格堆栈中的点数,包括零。为此我做了:
#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。我的错误是什么?
【问题讨论】: