How can I convert a data.frame
如何转换data.frame
df <- data.frame(id=c("af1", "af2"), start=c(100, 115), end=c(114,121))
To a list of lists
到列表列表
LoL <- list(list(id="af1", start=100, end=114), list(id="af2", start=115, end=121))
I've tried things like
我尝试过类似的东西
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
the not.LoL
that I currently have gives me the following error:
我目前拥有的not.LoL给了我以下错误:
> not.LoL[[1]]$start
Error in not.LoL[[1]]$start : $ operator is invalid for atomic vectors
Explanations and/or solutions would be greatly appreciated.
非常感谢解释和/或解决方案。
Edit: 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.
编辑:我应该明确这里的“id”实际上是非唯一的 - 在一个ID下可以有多个元素。所以我可以使用不依赖于唯一ID的解决方案来进行拆分。
3 个解决方案
#1
7
Using plyr
, you can do this
使用plyr,您可以这样做
dlply(df,.(id),c)
To avoid grouping by id , if there are multiple ( maybe you need to change column name , id is unique for me)
要避免按ID分组,如果有多个(可能需要更改列名,id对我来说是唯一的)
dlply(df,1,c)
#2
5
LMAo <- lapply(split(df,df$id), function(x) as.list(x)) # is one way
# more succinctly
# LMAo <- lapply(split(df,df$id), as.list)
An edited solution as per your comment:
根据您的评论编辑的解决方案:
lapply( split(df,seq_along(df[,1])), as.list)
#3
5
You can use apply
to turn your data frame into a list of lists like this:
您可以使用apply将数据框转换为列表列表,如下所示:
LoL <- apply(df,1,as.list)
However, this will change all your data to text, as it passes a single atomic vector to the function.
但是,这会将所有数据更改为文本,因为它将单个原子向量传递给函数。
#1
7
Using plyr
, you can do this
使用plyr,您可以这样做
dlply(df,.(id),c)
To avoid grouping by id , if there are multiple ( maybe you need to change column name , id is unique for me)
要避免按ID分组,如果有多个(可能需要更改列名,id对我来说是唯一的)
dlply(df,1,c)
#2
5
LMAo <- lapply(split(df,df$id), function(x) as.list(x)) # is one way
# more succinctly
# LMAo <- lapply(split(df,df$id), as.list)
An edited solution as per your comment:
根据您的评论编辑的解决方案:
lapply( split(df,seq_along(df[,1])), as.list)
#3
5
You can use apply
to turn your data frame into a list of lists like this:
您可以使用apply将数据框转换为列表列表,如下所示:
LoL <- apply(df,1,as.list)
However, this will change all your data to text, as it passes a single atomic vector to the function.
但是,这会将所有数据更改为文本,因为它将单个原子向量传递给函数。