R 计算网格中的物种发生率

R 计算网格中的物种发生率,r,r-raster,R,R Raster,我在全美一种候鸟物种的发生数据中有大约500000个点 我试图在这些点上覆盖一个网格,然后计算每个网格中出现的次数。计数完成后,我想将它们引用到网格单元ID 在R中,我使用了over()函数来获取范围贴图中的点,范围贴图是一个形状文件 #Read in occurrence data data=read.csv("data.csv", header=TRUE) coordinates(data)=c("LONGITUDE","LATITUDE") #Get shapefile of the s

我在全美一种候鸟物种的发生数据中有大约500000个点

我试图在这些点上覆盖一个网格,然后计算每个网格中出现的次数。计数完成后,我想将它们引用到网格单元ID

在R中,我使用了
over()
函数来获取范围贴图中的点,范围贴图是一个形状文件

#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
的点和栅格。您是否建议对光栅网格进行多边形化,并使用与我上面所述相同的方法?或者另一个流程会更高效吗?

首先,您的R代码没有按编写的那样工作。我建议将它复制粘贴到一个干净的会话中,如果它也为您出错,请更正语法错误或包括附加库,直到它运行为止

这就是说,我假设你应该得到一个二维数字坐标的
data.frame
。因此,为了对它们进行分类和计数,任何这样的数据都可以,所以我冒昧地模拟了这样一个数据集。如果这没有捕获数据的相关方面,请纠正我

## 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);
##如果您是OP,请跳过这一行,并替换实际数据。

数据你在使用哪个软件包?@HongOoi我相信它是
sp
。这可能会让你开始:你可能想玩
pracma
软件包,它有一个函数
inpolygon
,可以确定给定点是否在给定多边形的内部。我想这需要将光栅栅格转换为多边形阵列。@Hongoo我一直在寻找一种使用
graster
的方法,但也一直在使用
sp
-Victoria