Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Melt a dataframe using a list column

From a dataframe which has a column list:

`id text stock 
 1 text1 c("Google", "Yahoo")  
2  test  Yahoo`
data <- data.frame(id = c(1,2), text = c("text1", "test"), stock = c("c("Google", "Yahoo")", "Yahoo")

How could it be possible to melt this dataframe in this format
id text stock

`1  text1 Google 
1  text1 Yahoo 
2  test  Yahoo`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s a simple unnest() from tidyr:

library(tidyr)
dat <- tribble(~id, ~text, ~stock, 
               1, "text1", c("Google", "Yahoo"),
               2,  "test", "Yahoo")
unnest(dat, cols = stock)
#> # A tibble: 3 x 3
#>      id text  stock 
#>   <dbl> <chr> <chr> 
#> 1     1 text1 Google
#> 2     1 text1 Yahoo 
#> 3     2 test  Yahoo

PS, before posting, please check that your code actually creates a minimal sample dataset. Your line with data.frame is bugged.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading