将数据帧转换为列表

时间:2018-01-11 17:49:43

标签: r list dataframe

如何将data.frame转换为列表?

输入文件:

df
a item1
a item2
a item3
b item4
b item5

输出文件:

output
[[1]]
item1 item2 item3

[[2]]
item4 item5

我找到了相反的方法。但我无法弄清楚如何将其转换为列表。你能救我一下吗?

https://www.r-bloggers.com/r-combining-vectors-or-data-frames-of-unequal-length-into-one-data-frame/

1 个答案:

答案 0 :(得分:3)

您可以使用splitunstack

unstack(df, V2 ~ V1)
# $a
# [1] "item1" "item2" "item3"
# 
# $b
# [1] "item4" "item5"
#

with(df, split(V2, V1))
# $a
# [1] "item1" "item2" "item3"
#
# $b
# [1] "item4" "item5"
#

示例数据:

df <- structure(list(V1 = c("a", "a", "a", "b", "b"), V2 = c("item1", 
    "item2", "item3", "item4", "item5")), .Names = c("V1", "V2"), 
    row.names = c(NA, 5L), class = "data.frame")