Reputation: 2592
I am building a sp::SpatialLines
using spsample
. In the doc, it is written for spsample(x, n, type, ...)
:
type: character; "random" for completely spatial random; "regular" for regular (systematically aligned) sampling; [...]
Yet, I just realized that successively created lines with spsample
and type='regular'
between the very same two points were not identical:
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"
I have been fighting hard in my code to understand why measures of distances between (what should be) two same points and (what should be) two same lines did not give strictly identical results.
Any idea why is this so, and how to ensure consistent results between successive runs? (or: any alternative to build two identical lines in a similar spirit as above?)
Upvotes: 2
Views: 234
Reputation: 10340
That's some weird behavior. Although, if you put the seed before both samples, it will have no differences. Hence, it is probably due to the origin of the regular sampling varying slightly in the different runs.
....
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
As I have become a big fan of the sf
Package I tested whether this would have the same issues. Turns out it doesn't:
(don't get confused, there are some conversions between sf
and sp
objects, in order to stick as close to the code given in 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
Upvotes: 2