Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

r - Converting a data.frame to a list of lists

How can I convert a 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[[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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...