Fast way to save lines from coordinate groupings in R

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Fast way to save lines from coordinate groupings in R



I'm generating paths from jogging coordinates. A sample like what I have can be reproduced below:


#Reproduce Data
library(data.table)
library(sf)
dt <- data.table(lon=sample(c(380:390), 1000000, replace = TRUE)/10,lat=sample(c(80:90), 1000000, replace = TRUE)/10, pgrp=rep(c(1:100),10000))
tpathline <- st_as_sf(dt, coords = c("lon","lat"),crs=4326)



The below to compile the points in groups of lines takes FOREVER. I have a bunch of these to do, is there a faster/better way to compile lines than the dplyr pipe below?


#Works but slowest thing ever
library(dplyr)
baseline <- tpathline %>%
dplyr::group_by(pgrp) %>%
dplyr::summarise(do_union=F) %>%
sf::st_cast("MULTILINESTRING")



Thanks in advance!!!




2 Answers
2



This is my general approach when working with sf and data.table, and it's pretty quick too.


sf


data.table


library(data.table)
library(sf)
dt <- data.table(lon=sample(c(380:390), 1000000, replace = TRUE)/10,lat=sample(c(80:90), 1000000, replace = TRUE)/10, pgrp=rep(c(1:100),10000))

sf <- dt[
,
geometry <- sf::st_linestring(x = matrix(c(lon, lat), ncol = 2))
geometry <- sf::st_sfc(geometry)
geometry <- sf::st_sf(geometry = geometry)

, by = pgrp
]

sf <- sf::st_as_sf(sf)



As you're creating LINESTRINGs this assumes your data is ordered.



Maybe this?


library(data.table)
library(sf)
dt <- data.table(lon=sample(c(380:390), 1000000, replace = TRUE)/10,lat=sample(c(80:90), 1000000, replace = TRUE)/10, pgrp=rep(c(1:100),10000))

tpathline <- data.table(st_as_sf(dt, coords = c("lon","lat"),crs=4326))

lns = st_as_sf(tpathline[, list(geometry = st_cast(st_union(geometry), "LINESTRING")), by = pgrp])





I think there might be an error in here somewhere, as lns[['geometry']][[1]] == lns[['geometry']][[2]] gives [1] TRUE - i.e., all your lines are the same
– SymbolixAU
Aug 13 at 0:21



lns[['geometry']][[1]] == lns[['geometry']][[2]]


[1] TRUE





Thanks @SymbolixAU! You are right. Your answer seems to be the right approach to this.
– TimSalabim
Aug 13 at 16:39






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard