R Unnest dataframe column with list into two columns

Advertisements

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:

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])))

Leave a ReplyCancel reply