R 函数,用于围绕模式中的每个点创建圆盘,然后计算每个圆盘中的点数 [空间]

R function for creating discs around each point in a pattern, then counting number of points in each disc [spatial]

我正在尝试为图案中的每个点创建一个圆盘;每个圆盘将具有相同的半径。然后对于每个圆盘,我想计算落在圆盘内的点数。每个图案有 100-400 个点。我已经编写了代码来执行此操作,但是速度很慢。代码如下。我无法提供 shapefile 和点,因为那会非常困难,但如果需要,我可以创建一些虚拟数据。


  W <- as.owin(shape) 
  #Converts created .shp file into a "window" 
  #in which everything is plotted and calculated
  SPDF <- SpatialPointsDataFrame(P[,1:2], P) 
  #Converts data frame to spatial points data frame
  SP <- as(SPDF, "SpatialPoints") #Converts SPDF to spatial points
  SP1  <- as.ppp(coordinates(SP), W)

  SP2 <- as.ppp(SP1)

  attr(SP1, "rejects")
  attr(SP2, "rejects")  



  aw <- area.owin(W) #Area, in pixels squared, of leaf window created earlier
  #awm <- aw * (meas)^2 * 100 #Area window in millimeters squared

  # Trichome_Density_Count-----------------------------------------------------------------------------------------------

  TC <- nrow(P) #Counts number of rows in XY data points file,
  #this is number of trichomes from ImageJ

  TD <- TC/awm #Trichome density, trichomes per mm^2




#SPDF2 <- as.SpatialPoints.ppp(SP2)


#kg <- knn.graph(SPDF2, k = 1) 
#Creates the lines connecting each NND pairwise connection
#dfkg <- data.frame(kg) #Converts lines into a data frame
#dfkgl <- dfkg$length

meanlength <- 78

discstest <- discs(SP2, radii = meanlength, 
                   separate = TRUE, mask = FALSE, trim = FALSE,
                   delta = NULL, npoly=NULL) 
#Function creates discs for each trichome
#Using nearest neighbor lengths as radii


#NEED TO ADD CLIPPING

ratiolist <- c()

for (i in 1:length(discstest)) {



  ow2sp <- owin2SP(discstest[[i]])

  leafsp <- owin2SP(W)

  tic("gIntersection")

  intersect <-  rgeos::gIntersection(ow2sp, leafsp)

  Sys.sleep(1)
  toc()


  tic("over")


  res <- as.data.frame(sp::over(SP, intersect, returnList = FALSE))

  Sys.sleep(1)
  toc()

  res[is.na(res)] <- 0

  newowin <- as.owin(intersect)

  circarea <- area.owin(newowin)

  trichactual <- sum(res)

  trichexpect <- (TC / aw) * circarea

  ratio <- trichactual / trichexpect


  ratiolist[[i]] <- ratio


}

如果我对你的理解是正确的,你想遍历每个点并检查有多少点落在以该点为中心的半径为 R 的圆盘内。这在 spatstat 中使用函数 closepaircounts:

非常有效地完成
closepaircounts(SP2, r = meanlength)

这只是 returns 一个向量,对于 SP2.

中的每个点,半径为 r 的圆盘中包含的点数

我刚刚尝试了 100,000 个点,其中每个点周围的圆盘中平均有近 3000 个其他点,在我的笔记本电脑上花了 8 秒。如果你有更多的点,或者特别是如果圆盘半径太大以至于每个圆盘包含更多的点,计算起来可能会很慢。