Create path chain tibble from comma separated character vectors

Viewed 36

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)

1 Answers

Here's another way.

Create a column for row number, get the data in separate rows splitting on comma, for each row create a new column with the next value and drop NA values.

library(dplyr)

df %>%
  mutate(row = row_number()) %>%
  tidyr::separate_rows(chain) %>%
  group_by(row) %>%
  mutate(to = lead(chain)) %>%
  na.omit() %>%
  ungroup %>%
  select(-row, from = chain)

#  from  to   
#  <chr> <chr>
#1 A     B    
#2 B     C    
#3 C     D    
#4 X     Y    
#5 Y     Z    
Related