将数据框拆分为嵌套数据框和矩阵的列表 [英] Split a dataframe into a list of nested data frames and matrices
问题描述
我想将钻石
数据帧分成5个数据帧的列表,按 cut
分组.这条指令使我开始. https://dplyr.tidyverse.org/reference/group_split.html
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))
我想要的输出是5个嵌套列表的列表.每个嵌套列表都包含一个数据框和一个矩阵,例如:
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]
因此,每个嵌套列表(或每个 cut
)都包含一个n行数据框(取决于分类为该菱形的钻石数量),每行3列,命名因子为3n行乘10列名为mat.换句话说,列表的最低层(嵌套矩阵和数据框)在5个嵌套列表中应具有相同的名称.我该如何进行?
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?
谢谢.
推荐答案
您的意思是这样的吗?
result <- lapply(diamonds_g, function(x)
list(factors = x[2:4], mat = as.matrix(x[6:10])))
这篇关于将数据框拆分为嵌套数据框和矩阵的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!