在网格中统计物种出现次数

6

我手头有一份包含美国境内某候鸟物种出现数据的 R 代码,共约 50 万个点。

我想在这些点上叠加网格,并计算每个网格中出现的次数。完成计数后,我需要将其与网格单元 ID 相对应。

在 R 中,我使用了 over() 函数来获取范围图内的点,该图是一个 shapefile 文件。

#Read in occurrence data
data=read.csv("data.csv", header=TRUE)
coordinates(data)=c("LONGITUDE","LATITUDE")

#Get shapefile of the species' range map
range=readOGR(".",layer="data")

proj4string(data)=proj4string(range)

#Get points within the range map
inside.range=!is.na(over(data,as(range,"SpatialPolygons")))

上面的方法正如我所希望的那样运行,但没有解决我的当前问题:如何处理类型为“SpatialPointsDataFrame”的点和栅格。您是否建议将栅格化的栅格转换为多边形,并使用我上面提到的相同方法?还是另一个过程更有效?

你使用的是哪个包? - Hong Ooi
@HongOoi 我相信应该是 sp - agstudy
3
这可能会帮助你入门:使用 R 将点聚合到网格上 - Ben
你可能想尝试使用pracma包,它有一个名为inpolygon的函数,可以确定给定点是否在给定多边形的内部。我猜这需要将你的光栅网格转换成多边形数组。 - Carl Witthoft
@HongOoi一直在寻找使用raster实现它的方法,但也一直在使用sp - 维多利亚 - Victoria
1个回答

3
首先,你的R代码无法正常工作。我建议你将其复制并粘贴到一个干净的会话中,如果它也对你产生错误,就纠正语法错误或包含附加库直到它运行为止。
话虽如此,我假设你最终应该得到一个二维数字坐标的数据框。因此,为了进行分组和计数,任何这样的数据都可以使用,所以我冒昧地模拟了这样一个数据集。如果这不符合你数据的相关方面,请指出来。
## Skip this line if you are the OP, and substitute the real data instead.
data<-data.frame(LATITUDE=runif(100,1,100),LONGITUDE=runif(100,1,100));

## Add the latitudes and longitudes between which each observation is located
## You can substitute any number of breaks you want. Or, a vector of fixed cutpoints
## LATgrid and LONgrid are going to be factors. With ugly level names.
data$LATgrid<-cut(data$LATITUDE,breaks=10,include.lowest=T);
data$LONgrid<-cut(data$LONGITUDE,breaks=10,include.lowest=T);

## Create a single factor that gives the lat,long of each observation. 
data$IDgrid<-with(data,interaction(LATgrid,LONgrid));

## Now, create another factor based on the above one, with shorter IDs and no empty levels
data$IDNgrid<-factor(data$IDgrid); 
levels(data$IDNgrid)<-seq_along(levels(data$IDNgrid));

## If you want total grid-cell count repeated for each observation falling into that grid cell, do this:
data$count<- ave(data$LATITUDE,data$IDNgrid,FUN=length);
## You could have also used data$LONGITUDE, doesn't matter in this case

## If you want just a table of counts at each grid-cell, do this:
aggregate(data$LATITUDE,data[,c('LATgrid','LONgrid','IDNgrid')],FUN=length);
## I included the LATgrid and LONgrid vectors so there would be some 
## sort of descriptive reference accompanying the anonymous numbers in IDNgrid,
## but only IDNgrid is actually necessary

## If you want a really minimalist table, you could do this:
table(data$IDNgrid);

我对这个解决方案有一个后续问题,我已经发布在以下链接中:https://stackoverflow.com/questions/76383504/produce-heat-map-from-count-of-event-occurrences-in-grid?noredirect=1#comment134694099_76383504 - Rina Tse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接