Farge
Farge

Reputation: 23

"Undoing" a nested tibble created with stringr::str_split

I have created a nested tibble in R using stringr::str_split. Is there a more elegant way to go from the nested tibble to the "original" tibble than the solution I have presented below?

library(tidyverse)
# original tibble
df <- tibble(x = c("a", "b"),
             y = c("a1, a2", "b1, b2"))
df
#> # A tibble: 2 x 2
#>   x     y     
#>   <chr> <chr> 
#> 1 a     a1, a2
#> 2 b     b1, b2

# nested version
df_nested <- df %>% 
  mutate(y = str_split(y, ", "))
df_nested
#> # A tibble: 2 x 2
#>   x     y        
#>   <chr> <list>   
#> 1 a     <chr [2]>
#> 2 b     <chr [2]>

# to get back to original
mutate(df, y = unlist(lapply(y, paste0, collapse = ", ")))
#> # A tibble: 2 x 2
#>   x     y     
#>   <chr> <chr> 
#> 1 a     a1, a2
#> 2 b     b1, b2

Created on 2019-01-07 by the reprex package (v0.2.1)

Upvotes: 2

Views: 98

Answers (1)

akrun
akrun

Reputation: 887541

We can use map from purrr

library(tidyverse)
df_nested %>% 
     mutate(y = map_chr(y, toString))
# A tibble: 2 x 2
#  x     y     
#  <chr> <chr> 
#1 a     a1, a2
#2 b     b1, b2

Also, both the steps can be done with tidyverse in another way with separate_rows and group_by, summarise

df %>% 
  separate_rows(y) %>% # long format
  group_by(x) %>% 
  summarise(y = toString(y)) # wide format

Upvotes: 3

Related Questions