Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...