Home > OS >  Melt a dataframe using a list column
Melt a dataframe using a list column

Time:04-03

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`

CodePudding user response:

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.

  •  Tags:  
  • r
  • Related