问题
Could you please help me?
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))
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)
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))
.
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!
回答1:
You're almost there:
split(df$vertices, df$modules)
回答2:
> lapply(split(df, df$modules), "[", , 1)
$`1`
[1] "a" "e" "i" "m" "q"
$`2`
[1] "b" "f" "j" "n" "r"
$`3`
[1] "c" "g" "k" "o" "s"
$`4`
[1] "d" "h" "l" "p" "t"
来源:https://stackoverflow.com/questions/64523750/how-to-transform-a-data-frame-into-a-list-in-r