将data.frame转换为列表列表 [英] Converting a data.frame to a list of lists
问题描述
如何转换data.frame
How can I convert a data.frame
df <- data.frame(id=c("af1", "af2"), start=c(100, 115), end=c(114,121))
列表列表
LoL <- list(list(id="af1", start=100, end=114), list(id="af2", start=115, end=121))
已经尝试过如
not.LoL <- as.list(as.data.frame(t(df)))
我真的不知道这是什么结果,但不是完全正确。我的要求是,我可以通过命令访问第一个开始
and I'm really not sure what I end up with after this, but it isn't quite right. My requirement is that I can access, say, the first start
by the command
> LoL[[1]]$start
[1] 100
not.LoL
,我目前给了我以下错误:
the not.LoL
that I currently have gives me the following error:
> not.LoL[[1]]$start
Error in not.LoL[[1]]$start : $ operator is invalid for atomic vectors
解释和/或解决方案将不胜感激。
Explanations and/or solutions would be greatly appreciated.
编辑:我应该明确表示id这里实际上是非唯一的 - 在单个ID下可以有多个元素。所以我可以使用不依赖于 split
的唯一ID的解决方案。
I should have made it clear that "id" here is actually non-unique - there can be multiple elements under a single ID. So I could do with a solution that doesn't depend on unique IDs to split
on.
推荐答案
使用 plyr
可以这样做
dlply(df,.(id),c)
为了避免按ID分组,如果有(或许你需要更改列名,id对我来说是唯一的)
To avoid grouping by id , if there are multiple ( maybe you need to change column name , id is unique for me)
dlply(df,1,c)
这篇关于将data.frame转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!