Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting List to Vector using Tidyverse

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.

like image 834
Shige Song Avatar asked Dec 18 '25 13:12

Shige Song


2 Answers

Try

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

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

like image 79
Jan Kislinger Avatar answered Dec 21 '25 06:12

Jan Kislinger


Very nice. Also, within the tidyverse:

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

also works.

like image 44
Shige Song Avatar answered Dec 21 '25 06:12

Shige Song



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!