# R: converting coordinates point to coordinates lines - and retaining variables

I have a large dataset with the x,y coordinates of 91 different trajectories distinguished by the variable ID:

>     head(trjct)
t        x      y        z     Etot   ID
1 0.00 696621.4 167730 1680.960 1192.526 sim1
2 0.01 696621.4 167730 1680.959 1192.526 sim1
3 0.02 696621.4 167730 1680.958 1192.526 sim1
4 0.04 696621.4 167730 1680.952 1192.526 sim1
5 0.06 696621.4 167730 1680.942 1192.526 sim1
6 0.08 696621.4 167730 1680.929 1192.526 sim1


I have managed to convert these coordinates into lines:

  coordinates(trjct) <- ~x+y
trjct_lines_coords <- lapply(split(trjct, trjct$ID), function(x) Lines(list(Line(coordinates(x))), x$ID[1L])) #first column = row number


However the information contained within the variable Etot is not included. How can I create a list of lines, each with one line and corresponding Etot values in the list?

I want to create a data.frame for the lines, grouped by id (one row for each line) and I also want to keep the information contained in Etot.

Here is one way to do it with the sf package, which is good at dealing with geometrical and spatial data. Note that you need the development version of ggplot2 to use geom_sf for the plot. The approach is pretty simple and reflects how cool sf can be because it works well with other tidyverse tools. We use st_as_sf to convert to an sf object (put the point coordinates into a geometry column), group_by(ID) and summarise to collapse the points into a MULTIPOINT and Etot into one value, and then st_cast to convert the MULTIPOINT geometries into lines.

library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.0, proj.4 4.9.3
"t        z     Etot   ID
0.00 1680.960 1192.526 sim1
0.01 1680.959 1192.526 sim1
0.02 1680.958 1192.526 sim1
0.04 1680.952 1192.526 sim1
0.06 1680.942 1192.526 sim1
0.08 1680.929 1192.526 sim1"
)
#> Warning in rbind(names(probs), probs_f): number of columns of result is not
#> a multiple of vector length (arg 2)
#> Warning: 1 parsing failure.
#> row # A tibble: 1 x 5 col     row col   expected actual        file         expected   <int> <chr> <chr>    <chr>         <chr>        actual 1     6 ID    ""       embedded null literal data file # A tibble: 1 x 5

lines <- tbl %>%
st_as_sf(coords = c("t", "z")) %>%
group_by(ID) %>%
summarise(Etot = mean(Etot)) %>%
st_cast("LINESTRING")

ggplot(lines) +
theme_bw() +
geom_sf()


Created on 2018-03-13 by the reprex package (v0.2.0).