конверт для Foxall Jfox с "ошибкой в ​​Hest" в R spatstat - PullRequest
0 голосов
/ 18 февраля 2020

Я хочу исследовать расстояние между точками в точечном образце до ближайшего многоугольника в шейп-файле многоугольника.

Используя пакет R spatstat, мой подход заключается в вычислении envelope для функции Jfox, которые учитывают расстояние моих точек до полигонов.

Мой полный набор данных содержит точечные шаблоны с нескольких сайтов, и я успешно использую этот подход с несколькими сайтами.

Однако при запуске конверта на определенном сайте я получаю эту ошибку:

Generating 99 simulations of CSR with fixed number of points  ...
Error : in Hest(X,r) the successive r values must be finely spaced: given spacing = 0.0043766; required spacing <=  0.00393
In addition: Warning messages:
1: In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
2: In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
[retrying]
Error : in Hest(X,r) the successive r values must be finely spaced: given spacing = 0.0043766; required spacing <=  0.00393
In addition: Warning message:
In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
[retrying]
... and so on.

Я не могу понять, что является причиной проблемы.

Воспроизводимый пример:

Файлы данных можно найти здесь:

https://www.dropbox.com/sh/fzucl5f6u4s2igx/AAAzgf2Fn-L9cfwzSCwj1RbPa?dl=0

пожалуйста, адаптируйте код для импорта данных в зависимости от того, где вы храните файлы.


library(tidyverse)
{ # load these two together because spatstat rely on them but I don't know exactely for what.
library(sp)
library(maptools)  # needed for method such as as.ppp
}
library(spatstat)
library(sf)
library(xlsx)

# load transect polygon giving the Window of ppp, and make it a owin object
tr_poly_win<-st_read('transect.shp') %>%
             select(geometry) %>% as(., 'Spatial') %>% as(.,'SpatialPolygons') %>%
             as.owin(tr_poly_sp)

# load points and make them a ppp with correct window

options(digits=15) # this to allow enough decimals
points<-read.table('points.txt', head=T,sep='\t',dec='.') %>%
        mutate(geometry=as.character(geometry)) %>%
        mutate(lon=as.numeric(sapply(strsplit(geometry, '[(,)]'), "[[", 2)), 
               lat=as.numeric(sapply(strsplit(geometry, '[(,)]'), "[[", 3))) %>%
        st_as_sf(coords=c('lon','lat'),crs= 32619) %>%
        as(.,'Spatial') %>%
        as.ppp(.)

Window(points)<-tr_poly_win

# load polygons
win<-st_read('polygons.shp') %>% as(.,'Spatial') %>% as(.,'owin')

# create an hyperframe

hyp<-hyperframe(points=points,win=win)

# visualize data:
# points as open circles; points' window as black contour; polygons in red; 
# Frame of the polygons as red rectangle; Frame of points as green rectangle
plot(hyp, quote({plot(points,which.marks='pos',type='n')
                 plot(win,col=2,add=TRUE)
                 plot(points,which.marks='pos',type='p', add=T)
                 plot(Frame(win),border=2, add=T) 
                 plot(Frame(points),border=3, add=T)}) )

enter image description here

точки в виде открытых кружков; окно точек в виде черного контура; многоугольники в красном; Каркас полигонов в виде красного прямоугольника; Рамка из точек в виде зеленого прямоугольника

# computing the Jfox function works
with(hyp,Jfox(points,win))

# try to compute the envelope for the Jfox and you'll get the error
with(hyp,envelope(Y=points,  fun=Jfox, funargs=list(Y=win) , nsim=99, fix.n=T))

Существует ли какая-либо причина, по которой я получаю эту ошибку или это ошибка (например, см. Ссылки в PS )?

Информация о моем сеансе выглядит следующим образом:

R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] xlsx_0.6.1          sf_0.7-4            spatstat_1.63-0     rpart_4.1-15        nlme_3.1-140        spatstat.data_1.4-3 maptools_0.9-5      sp_1.3-1            forcats_0.4.0      
[10] stringr_1.4.0       dplyr_0.8.3         purrr_0.3.3         readr_1.3.1         tidyr_1.0.0         tibble_2.1.3        ggplot2_3.2.1       tidyverse_1.2.1    

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1            lubridate_1.7.4       lattice_0.20-38       deldir_0.1-16         xlsxjars_0.6.1        class_7.3-15          assertthat_0.2.1      zeallot_0.1.0        
 [9] R6_2.4.0              cellranger_1.1.0      backports_1.1.4       e1071_1.7-1           httr_1.4.1            tensor_1.5            pillar_1.4.0          rlang_0.4.1          
[17] lazyeval_0.2.2        readxl_1.3.1          rstudioapi_0.10       Matrix_1.2-18         goftest_1.2-2         splines_3.6.2         rgdal_1.4-3           foreign_0.8-72       
[25] polyclip_1.10-0       munsell_0.5.0         broom_0.5.2           compiler_3.6.2        modelr_0.1.5          pkgconfig_2.0.2       mgcv_1.8-31           tidyselect_0.2.5     
[33] crayon_1.3.4          withr_2.1.2           grid_3.6.2            jsonlite_1.6          gtable_0.3.0          lifecycle_0.1.0       DBI_1.0.0             magrittr_1.5         
[41] units_0.6-3           scales_1.0.0          KernSmooth_2.23-16    cli_1.1.0             stringi_1.4.3         xml2_1.2.2            spatstat.utils_1.17-0 generics_0.0.2       
[49] vctrs_0.2.0           tools_3.6.2           glue_1.3.1            hms_0.5.2             abind_1.4-5           colorspace_1.4-1      classInt_0.3-3        rvest_0.3.5          
[57] rJava_0.9-11          haven_2.2.0          

Ps: Мой поиск объяснения привел к аналогичным проблемам, которые возникли в результате ошибки в предыдущей версии кода spatstat. вот ссылки:

http://r-sig-geo.2731867.n2.nabble.com/Error-in-random-labelling-using-the-J-function-td7593210.html

http://r-sig-geo.2731867.n2.nabble.com/Complete-spatial-randomness-testing-td7590425.html

Как вы можете видеть, мой statspat и мои версии R должны быть текущими.

1 Ответ

1 голос
/ 20 февраля 2020

Это ошибка.

Теперь это исправлено в версии для разработчиков spatstat (версия 1.63-0.020 и выше), доступной в репозитории на GitHub .

...