Nathalie
Nathalie

Reputation: 1238

Unlist a column of a dataframe

Having this dataframe

df <- structure(list(date = c("2008-07-31", "2008-08-04"), id = c(1L, 
                                                                  1L), body = list("text 2 and here another", 
                                                                                   c("another text here", 
                                                                                     "and this in the same row", 
                                                                                     "one more in the same row"
                                                                                   ))), row.names = 1:2, class = "data.frame")

How is it possible to unlist the body column to have an output like this:

 date id                                                                  body
1 2008-07-31  1                                               text 2 and here another
2 2008-08-04  1 another text here and this in the same row one more in the same row

I tried this:

df$body <- as.data.frame(unlist(df$body))

Upvotes: 1

Views: 88

Answers (2)

GKi
GKi

Reputation: 39657

You can use paste in sapply.

df$body <- sapply(df$body, paste, collapse = " ")
str(df$body)
# chr [1:2] "text 2 and here another" ...

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

With dplyr and purrr, you can do:

df %>%
 mutate(body = map_chr(body, paste, collapse = " "))

        date id                                                                body
1 2008-07-31  1                                             text 2 and here another
2 2008-08-04  1 another text here and this in the same row one more in the same row

Upvotes: 1

Related Questions