首页 > 解决方案 > 无法将列表转换为数据框

问题描述

我有一个名为 my_list 的列表,如下所示:

$love 
playing working sleeping 
   0.43    0.56     0.88
$will 
otherwise rework rule 
    0.87    0.23  0.11
$new
car  shirt
0.23   0.12

我想将其转换为以下数据框,输出如下所示:

Column 1 Column 2 Column 3 
love     playing     0.43
love     working     0.56
love     sleeping    0.88
will     otherwise   0.87
will     rework      0.23
will     rule        0.11
new      car         0.23
new      shirt       0.12

我试过这个

  df <- do.call(rbind,lapply(cor1,as.data.frame))

但随后这些列成为数据框的默认列:

love.playing 0.43 
love.working .56

依此类推(基本上我只有一列带有数字)。任何帮助都感激不尽。

标签: rlistdataframetranspose

解决方案


out <- stack(my_list)
out$col2 <- row.names(out)
row.names(out) <- NULL
out
#   values  ind      col2
# 1   0.43 love   playing
# 2   0.56 love   working
# 3   0.88 love  sleeping
# 4   0.87 will otherwise
# 5   0.23 will    rework
# 6   0.11 will      rule
# 7   0.23  new       car
# 8   0.12  new     shirt

可重现的数据(请下次分享):

my_list <- list(
  love = c(playing = 0.43, working = 0.56, sleeping = 0.88),
  will = c(otherwise = 0.87, rework = 0.23, rule = 0.11),
  new = c(car = 0.23, shirt = 0.12)
)

推荐阅读