Split a dataframe into a list of nested data frames and matrices

ε祈祈猫儿з 提交于 2021-02-20 03:46:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!