Converting List to Vector using Tidyverse

1.6k views Asked by At

Here is a simple example from "R for Data Science":

df <- tribble(
  ~x1,
  "a,b,c",
  "d,e,f,g"
)

Now I can create a list-column like this:

df <- df %>%
  mutate(x2 = stringr::str_split(x1, ","))

Now the data looks like this:

# A tibble: 2 × 2
       x1        x2
    <chr>    <list>
1   a,b,c <chr [3]>
2 d,e,f,g <chr [4]>

Here is the question: If I only have x2, how can I recover x1 from it?

unnest() does not work because it changes the shape of the data.

2

There are 2 answers

1
Shige Song On

Very nice. Also, within the tidyverse:

df <- df %>% 
  mutate(x3 = map_chr(x2, stringr::str_c, collapse = ','))
df

also works.

4
Jan Kislinger On

Try

df %>% 
  mutate(x1_new = map_chr(x2, paste, collapse = ','))

(I assume you have loaded package purrr since you've mentioned tidyverse)