sp :: spsample(...,...,type ='regular')仍有一些随机性

问题描述 投票:2回答:1

我正在使用sp::SpatialLines建立一个spsample。在文档中,它是为spsample(x, n, type, ...)编写的:

类型:字符;完全空间随机的“随机”;定期(系统对齐)抽样的“常规”; [...]

然而,我只是意识到在相同的两点之间连续创建的spsampletype='regular'的行不完全相同:

library(sp)
set.seed(12)
for (i in 1:10) {
  p1 = c(400000, 401000)
  p2 = c(5600000, 5601000)
  l1 = as.data.frame(spsample(SpatialLines(list(Lines(Line(cbind(p1, p2)), ID="a"))), 
                              10000, "regular"))
  l2 = as.data.frame(spsample(SpatialLines(list(Lines(Line(cbind(p1, p2)), ID="a"))), 
                              10000, "regular"))
  print(all.equal(l1, l2))
}
# [1] "Component “p1”: Mean relative difference: 1.8687e-07"
# [1] "Component “p1”: Mean relative difference: 1.680998e-07"
# [1] "Component “p1”: Mean relative difference: 3.382085e-08"
# [1] "Component “p1”: Mean relative difference: 1.155756e-07"
# [1] TRUE
# [1] "Component “p1”: Mean relative difference: 1.051644e-07"
# [1] TRUE
# [1] "Component “p1”: Mean relative difference: 4.354955e-08"
# [1] "Component “p1”: Mean relative difference: 2.074916e-08"
# [1] "Component “p1”: Mean relative difference: 1.380726e-07"

我在我的代码中一直在努力去理解为什么两个相同的点之间的距离(应该是)和两个相同的线之间的距离的测量没有给出严格相同的结果。

知道为什么会这样,以及如何确保连续运行之间的一致结果? (或者:以与上述类似的精神构建两条相同的线条的任何替代方案?)

r sp
1个回答
2
投票

这是一些奇怪的行为。虽然,如果你把种子放在两个样本之前,它将没有差别。因此,可能是由于常规采样的起源在不同的运行中略有不同。

....
  set.seed(12)
  l1 = as.data.frame(spsample(SpatialLines(list(Lines(Line(cbind(p1, p2)), ID="a"))), 
                              10000, "regular"))
  set.seed(12)
  l2 = as.data.frame(spsample(SpatialLines(list(Lines(Line(cbind(p1, p2)), ID="a"))), 
                              10000, "regular"))
....
# [1] TRUE
# [1] TRUE
# [1] TRUE
....

sf as an alternative to sp

由于我已经成为sf包的忠实粉丝,我测试了它是否会出现同样的问题。事实证明它没有: (不要混淆,sfsp对象之间有一些转换,以便尽可能贴近OP中给出的代码)

library(sf)
library(dplyr)
library(sp)

set.seed(12)
for (i in 1:10) {
  p1 <- c(400000, 401000)
  p2 <- c(5600000, 5601000)
  l1 <- as.data.frame(
    st_as_sf(SpatialLines(list(Lines(Line(cbind(p1, p2)), ID="a"))) %>% 
      st_make_grid(n=100, what = "centers") %>% 
      as("Spatial")
  )
  l2 <- as.data.frame(
    st_as_sf(SpatialLines(list(Lines(Line(cbind(p1, p2)), ID="a"))) %>% 
      st_make_grid(n=100, what = "centers") %>% 
      as("Spatial")
  )
  print(all.equal(l1, l2))
}

# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
© www.soinside.com 2019 - 2024. All rights reserved.