Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

reshape2 - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...