问题
I'd like to split the diamonds
data frame into a list of 5 dataframe, group by cut
. This instruction got me started.
https://dplyr.tidyverse.org/reference/group_split.html
diamonds_g <- diamonds%>% group_split(cut)%>% setNames(unique(diamonds$cut))
My desired output is a list of 5 nested lists. Each nested list contains one data frame and one matrix, such that:
View(diamonds_g[[1]])
factors <- diamonds_g[[1]][2:4]
mat <- diamonds_g[[1]][6:10]
So each of the nested list (or each cut
) contains one data frame of n rows (depending on how many diamonds are classified as that cut) named factors by 3 columns, and one matrix of n rows by 10 columns named mat. In other words, the lowest level of the list (the nested matrix and data frame) should have identical names across the 5 nested lists. How do I proceed?
Thank you.
回答1:
Do you mean something like this?
result <- lapply(diamonds_g, function(x)
list(factors = x[2:4], mat = as.matrix(x[6:10])))
回答2:
We can use tidyverse
library(dplyr)
library(purrr)
result <- map(diamonds_g, ~ list(factors = .x[2:4], mat = as.matrix(.x[6:10])))
来源:https://stackoverflow.com/questions/65120387/split-a-dataframe-into-a-list-of-nested-data-frames-and-matrices