簡體   English   中英

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)

這只是返回一個向量,該向量包含SP2每個點的半徑為r的圓盤中包含的點數。

我剛剛嘗試了 100,000 個點,其中每個點在它周圍的光盤上平均有近 3000 個其他點,在我的筆記本電腦上花了 8 秒。 如果你有更多的點,或者特別是如果圓盤半徑太大以至於每個圓盤包含更多的點,計算這個可能會變得非常慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM