The task I'm trying to do is very simple with the sp
package in R but I'm trying to learn sf
hence my question. I'm trying to create a shape of points in R. I have lots of points so it has to be efficient. I've succeeded doing it in both sp
and sf
but the sf method is slow. Being new to sf
, I have a feeling I'm not doing it the most efficient way.
I've made 3 different functions which do the same thing:
1) 100% sp
f_rgdal <- function(dat) {
coordinates(dat) <- ~x+y
}
2) 100% sf
(probably bad...)
f_sf <- function(dat) {
dat <- st_sfc(
lapply(
apply(dat[,c("x", "y")], 1, list), function(xx) st_point(xx[[1]])
)
)
}
3) mix of both:
f_rgdal_sp <- function(dat) {
coordinates(dat) <- ~x+y
dat <- as(dat, "sf")
}
If I benchmark them, you can see that both function 2 and 3 are way slower than function 1:
set.seed(1234)
dd <- data.frame(x = runif(nb_pt, 0, 100),
y = runif(nb_pt, 0,50),
f1 = rnorm(nb_pt))
library(sp)
library(sf)
library(rbenchmark)
benchmark(f_rgdal(dd), f_sf(dd), f_rgdal_sp(dd), columns = c("test", "elapsed"))
test elapsed
1 f_rgdal(dd) 0.22
3 f_rgdal_sp(dd) 4.82
2 f_sf(dd) 4.08
Is their a way to speed up sf
? At the end, I want to use st_write
which is faster then writeOGR
so staying in sp
is not ideal.