2

How can you convert a data.frame into a list?

Input file:

df
a item1
a item2
a item3
b item4
b item5

output file:

output
[[1]]
item1 item2 item3

[[2]]
item4 item5

I found a way to do the opposite. But I cannot figure out how I can convert it into list. Can you help me out?

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

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
John
  • 79
  • 1
  • 1
  • 7

1 Answers1

3

You can use split or unstack:

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"
#

Sample data:

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")
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485