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

R Unnest dataframe column with list into two columns

I have a dataframe with a list in one of the columns. The list has a code and a date. I want to transform this list into two columns, one with the code and the second one with the date.

Here is some sample data:

input=structure(list(data = c("24/05/2024", "24/05/2024", "24/05/2024","24/05/2024", "24/05/2024"), 
                     contrato = c("DI1", "DI1", "DI1","DI1", "DI1"), 
                     venc = list(c("M24", "03/06/2024"), c("N24", "01/07/2024"), c("Q24", "01/08/2024"), c("U24", "02/09/2024"), c("V24", "01/10/2024")), 
                     preco_ajuste = c("99803,97", "99024,23", "98137,14", "97296,68","96499,71")), 
             class = c("data.table", "data.frame"), row.names = c(NA,-5L))

and the desired output:

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

output=structure(list(data = c("24/05/2024", "24/05/2024", "24/05/2024", "24/05/2024", "24/05/2024"),
                      contrato = c("DI1", "DI1", "DI1", "DI1", "DI1"), 
                      venc = c("M24", "N24", "Q24", "U24", "V24"), 
                      data_vcto = c("03/06/2024", "01/07/2024", "01/08/2024", "02/09/2024", "01/10/2024"), 
                      preco_ajuste = c("99803,97","99024,23", "98137,14", "97296,68", "96499,71")), 
                 class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -5L), 
                 groups = structure(list(data = "24/05/2024", .rows = structure(list(1:5), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"

>Solution :

venc_df <- do.call(rbind, lapply(input$venc, function(x) data.frame(symbol = x[1], date = x[2])))
output <- input %>%
  select(-venc) %>%
  bind_cols(venc_df)

or

venc_df <- data.table::rbindlist(lapply(input$venc, function(x) data.frame(symbol = x[1], date = x[2])))
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