如何在不同的顺序嵌套列表中分组一组data.frame对象? [英] How to group set of data.frame objects in nested list with different order?
问题描述
我在嵌套列表中设置了数据框架对象,我想按照data.frame对象的名称进行分组。因为每个嵌套列表,data.frame对象都以不同的顺序放置,所以我很难将它们分组到新列表中。我尝试从CRAN中的purr包中的转置方法,但是这并不是正确的答案。有没有人知道对data.frame对象进行这种分组的任何技巧呢?感谢很多
I have set of data.frame object in nested list, I want to group them by name of data.frame object. Because each nested list, data.frame objects are placed in different order, I have difficulty to group them in new list. I tried transpose method from purr packages in CRAN, but it wasn't right answer that I expected. Does anyone knows any trick of doing this sort of grouping for data.frame object more efficiently? Thanks a lot
res_1 <- list(con=list(a.con_1=airquality[1:4,], b.con_1=iris[2:5,], c.con_1=ChickWeight[3:7,]),
dis=list(a.dis_1=airquality[5:7,], b.dis_1=iris[8:11,], c.dis_1=ChickWeight[12:17,]))
res_2 <- list(con=list(b.con_2=iris[7:11,], a.con_2=airquality[4:9,], c.con_2=ChickWeight[2:8,]),
dis=list(b.dis_2=iris[2:5,], a.dis_2=airquality[1:3,], c.dis_2=ChickWeight[12:15,]))
res_3 <- list(con=list(c.con_3=ChickWeight[10:15,], a.con_3=airquality[2:9,], b.con_3=iris[12:19,]),
dis=list(c.dis_3=ChickWeight[2:7,], a.dis_3=airquality[13:16,], b.dis_3=iris[2:7,]))
所需输出:
desired output:
group1_New <- list(con=list(a.con_1, a.con_2, a.con_3),
dis=list(a.dis_1, a.dis_2, a.dis_3))
group2_New <- list(con=list(b.con_1, b.con_2, b.con_3),
dis=list(b.dis_1, b.dis_2, b.dis_3))
group3_New <- list(con=list(c.con_1, c.con_2, c.con_3),
dis=list(c.dis_1, c.dis_2, c.dis_3))
推荐答案
这是一个两次嵌套的for循环,创建所需的结构。有可能是一种更有效的方法。
Here is a twice nested for loop that creates the desired structure. There is likely a more efficient method.
# put the nested lists into a list:
myList <- list(res_1, res_2, res_3)
# make a copy of the list to preserve the structure for the new list
myList2 <- myList
for(i in seq_len(length(myList))) {
# get ordering of inner list names
myOrder <- rank(names(myList[[c(i,2)]]))
for(j in seq_len(length(myList[[i]]))) {
for(k in seq_len(length(myList[[c(i, j)]]))) {
# reorder content
myList2[[c(myOrder[k], j, i)]] <- myList[[c(i, j, k)]]
# rename element
names(myList2[[c(myOrder[k], j)]])[i] <- names(myList[[c(i, j)]])[k]
}
}
}
如果需要,您可以在循环后提取列表项。
If desired, you could extract the list items after the loops.
此解决方案的关键在于实现如果将这些列表放入列表中,则可以通过有选择地将列表项。通过选择性地,我的意思是我在数据框架名称上包含等级
,以找到最内层循环的正确顺序。
The key to this solution is the realization that if you put these lists into a list, the result can be achieved by selectively reversing the indices of the list items. By selectively, I mean that I incorporate rank
on the data.frame names to find the proper order for the inner-most loop.
除了根据需要重新排序data.frames,我还包括一行,以正确地重置列表中的名称。
In addition to reordering the data.frames as desired, I included a line to properly reset the names within the list.
这篇关于如何在不同的顺序嵌套列表中分组一组data.frame对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!