简体   繁体   中英

data.frame to list in R

I have data like this:

ID   = c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
item = c("a","b","c","a","c","a","b","a")

df = data.frame(ID,item)

ID1 a
ID1 b
ID1 c
ID2 a
ID2 c
ID3 a
ID4 b
ID4 a

and I would need it as a list like this to be transformed to "transactions":

[[1]]
[1] "a" "b" "c"
[[2]]
[1] "a" "c"
[[3]]
[1] "a"
[[4]]
[1] "b" "a"

I tried:

lapply(split(item, ID), function(x) as.list(x))

but the items are still on separate "rows" and not one after the other.

Any ideas on how to accomplish the above format?

Use unstack :

df <- data.frame(ID,item)
unstack(df, item~ID)
# $ID1
# [1] "a" "b" "c"
# 
# $ID2
# [1] "a" "c"
# 
# $ID3
# [1] "a"
# 
# $ID4
# [1] "b" "a"

Based on the expected output, you don't need to use as.list

setNames(split(as.character(df1$item),df1$ID) , NULL)
#[[1]]
#[1] "a" "b" "c"

#[[2]]
#[1] "a" "c"

#[[3]]
#[1] "a"

#[[4]]
#[1] "b" "a"

Using your approach and make it working:

> lapply(split(df, df$ID), function(u) u$item)
#$ID1
#[1] "a" "b" "c"

#$ID2
#[1] "a" "c"

#$ID3
#[1] "a"

#$ID4
#[1] "b" "a"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM