如何在R中将数据帧转换为列表? [英] How to transform a data frame into a list in r?
问题描述
能请你帮我吗?
我想根据R数据帧中包含的信息列出一个列表.我找到了解决方案,但这不是一般的解决方法.
I want to make a list based on information contained in an R data frame. I found a solution, but it is not general.
例如,让我们从以下数据框开始:
For instance, let's start with this data frame:
df <- data.frame(vertices = paste(letters[1:20]), modules = rep(1:4, 5))
我想使用 df $ modules
将数据框转换为列表.列表中的项目应包含来自 df $ vertices
的数据.所以我找到了解决方案:
I want to use df$modules
to turn the data frame into a list. The items of the list should contain data from df$vertices
. So I found this solution:
list1 <- split(df, df$modules)
list2 <- vector(mode = "list", length = length(unique(df$modules)))
list2[[1]] <- as.vector(list1[[1]]$vertices)
list2[[2]] <- as.vector(list1[[2]]$vertices)
list2[[3]] <- as.vector(list1[[3]]$vertices)
list2[[4]] <- as.vector(list1[[4]]$vertices)
如您所见,它可以工作,但不是通用的,因为您需要在代码的末尾手动添加很多行作为 length(unique(df $ modules))
.
As you can see, it works, but it's not general, because you need to manually add so many lines to the code's end as length(unique(df$modules))
.
我也尝试了while循环,但是没有用:
I've also tried a while loop, but it didn't work:
i <- 1
while (i == length(list2)) {
list2[[i]] <- as.vector(list1[[i]]$vertices)
list2
}
是否有解决此问题的一般方法?谢谢!
Is there a general solution to this problem? Thank you!
推荐答案
您快到了:
split(df$vertices, df$modules)
这篇关于如何在R中将数据帧转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!