Sf: Casting POINTS to LINESTRING reorders values

Created on 30 Mar 2018  路  1Comment  路  Source: r-spatial/sf

I'd like to convert my sf object (animal trajectories) from POINTS to LINESTRING. However, if I do so using st_cast("LINESTRING") the points are connected in a completely different order. Let me illustrate with some dummy data.

library(dplyr)
library(sf)
library(ggplot2) # newest version from github

df <- data.frame(theta = seq(0,10*pi,0.1)[1:300]) %>%
  mutate(
    r = 2 + 3*theta,
    x = r*cos(theta),
    y = r*sin(theta),
    group = c(rep("A",150),rep("B",150))
  )

ggplot(df, aes(x,y,colour = group)) +geom_path()

This gives me the following nice spiral.

drunk1

However, when I cast it to a LINESTRING, the order is completly different (left to right?). Am I doing something wrong?

df %>%
  st_as_sf(coords = c("x", "y"), agr = "constant") %>%
  group_by(group) %>%
  summarise() %>%
  st_cast("LINESTRING") %>%
  ggplot(aes(colour = group)) + 
  geom_sf()

drunk2

Some background: I'm just trying to plot my trajectories with tmap, which seemingly cannot plot lines from points.

Most helpful comment

My bad, just found the solution (#331) . My code was missing the argument do_union = FALSE within summarise(). It now works as expected.

drunk %>%
  st_as_sf(coords = c("x", "y"), agr = "constant") %>%
  group_by(group) %>%
  summarise(do_union = FALSE) %>%
  st_cast("LINESTRING") %>%
  ggplot(aes(colour = group)) + 
  geom_sf()

drunk3

>All comments

My bad, just found the solution (#331) . My code was missing the argument do_union = FALSE within summarise(). It now works as expected.

drunk %>%
  st_as_sf(coords = c("x", "y"), agr = "constant") %>%
  group_by(group) %>%
  summarise(do_union = FALSE) %>%
  st_cast("LINESTRING") %>%
  ggplot(aes(colour = group)) + 
  geom_sf()

drunk3

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kendonB picture kendonB  路  3Comments

ekarsten picture ekarsten  路  4Comments

duleise picture duleise  路  3Comments

happyshows picture happyshows  路  3Comments

kendonB picture kendonB  路  3Comments