I want to build a chain of dependencies between different geographical points. The tibble contains a single column with the paths separated by commas (,)
I have a dataset with this structure:
library(tidyverse)
(df <- tribble(~chain,
"A,B,C,D",
"X,Y,Z"))
#> # A tibble: 2 x 1
#> chain
#> <chr>
#> 1 A,B,C,D
#> 2 X,Y,Z
This is what I expect:
tribble(~from, ~to,
"A", "B",
"B", "C",
"C", "D",
"X", "Y",
"Y", "Z")
# expected result
#> # A tibble: 5 x 2
#> from to
#> <chr> <chr>
#> 1 A B
#> 2 B C
#> 3 C D
#> 4 X Y
#> 5 Y Z
This is my proposed solution:
# my solution:
(routes <- df %>%
group_by(chain) %>%
summarise(destino = str_split(chain, ",")) %>%
mutate(
from = map(destino, ~ lag(.x)) %>%
map(~ .x[!is.na(.x)]),
to = map(destino, ~ lead(.x)) %>%
map(~ .x[!is.na(.x)])) %>%
select(from, to) %>%
unnest(cols = everything()))
#> # A tibble: 5 x 2
#> from to
#> <chr> <chr>
#> 1 A B
#> 2 B C
#> 3 C D
#> 4 X Y
#> 5 Y Z
Is it possible to obtain this same result in another way? Maybe with a for loop?
Created on 2020-06-18 by the reprex package (v0.3.0)