Search code examples
rreshape2

R List of lists to dataframe with list name as extra column


I have a list of lists that have names.

I want to add them all together into a dataframe but keep all the columns

past_earnings_lists[1]

successfully returns one list from the list of lists

names(past_earnings_lists)[1]

successfully returns the name of the list

past_earnings <- melt(past_earnings_lists)

puts all the data in one data frame but doesn't keep structure

past_earnings <- as.data.frame.matrix(past_earnings_lists$ADBE)

Successfully takes one list and keeps the structure but doesn't add the name of the list to the dataframe.

For example, adbe has 7 columns and 30 rows; I want it to add an 8th column with the name, adbe, and append it to a dataframe with all the other lists doing the same.

structure

I want a dataframe with the results being:
  sym  v1 v2 v3 v4 v5 v6 v7
1 adbe  1  2  3  4  5  6  7
2 adbe  1  2  3  4  5  6  7
3 air   1  2  3  4  5  6  7
4 air   1  2  3  4  5  6  7
5 alog  1  2  3  4  5  6  7
and so on

Solution

  • This might work

    library(purrr)
    ans <- map_df(past_earnings_lists, ~as.data.frame(.x), .id="id")
    

    It uses map_df, which will map over lists and convert the result to data frames (if possible). Use the .id argument to add names to each data frame as a column.