首页 > 解决方案 > 如何在 r 的列表中收集类似的列表?

问题描述

我有一个包含复杂月份的列表。我想在一个列表中收集相同的月份。列表中的一月元素,列表中的二月元素等......

这是我的数据;

$`01-2011`
        date   V1
1 01-01-2011 1.48
2 01-02-2011 2.53

$`01-2012`
          date   V1
366 01-01-2012 0.14
367 01-02-2012 1.18

$`02-2015`
           date    V1
1493 02-01-2015 10.06
1494 02-02-2015  0.51

$`02-2016`
           date   V1
1858 02-01-2016 0.00
1859 02-02-2016 2.28

和数据结构;

mix<-list(`01-2011` = structure(list(date = c("01-01-2011", "01-02-2011"
), V1 = c(1.48, 2.53)), row.names = 1:2, class = "data.frame"), 
    `01-2012` = structure(list(date = c("01-01-2012", "01-02-2012"
    ), V1 = c(0.14, 1.18)), row.names = 366:367, class = "data.frame"), 
    `02-2015` = structure(list(date = c("02-01-2015", "02-02-2015"
    ), V1 = c(10.06, 0.51)), row.names = 1493:1494, class = "data.frame"), 
    `02-2016` = structure(list(date = c("02-01-2016", "02-02-2016"
    ), V1 = c(0, 2.28)), row.names = 1858:1859, class = "data.frame"))

期望的输出;

$jan
$jan$`01-2011`
        date   V1
1 01-01-2011 1.48
2 01-02-2011 2.53

$jan$`01-2012`
          date   V1
366 01-01-2012 0.14
367 01-02-2012 1.18


$feb
$feb$`02-2015`
           date    V1
1493 02-01-2015 10.06
1494 02-02-2015  0.51

$feb$`02-2016`
           date   V1
1858 02-01-2016 0.00
1859 02-02-2016 2.28

所需的输出结构;

out<-list(jan = list(`01-2011` = structure(list(date = c("01-01-2011", 
"01-02-2011"), V1 = c(1.48, 2.53)), row.names = 1:2, class = "data.frame"), 
    `01-2012` = structure(list(date = c("01-01-2012", "01-02-2012"
    ), V1 = c(0.14, 1.18)), row.names = 366:367, class = "data.frame")), 
    feb = list(`02-2015` = structure(list(date = c("02-01-2015", 
    "02-02-2015"), V1 = c(10.06, 0.51)), row.names = 1493:1494, class = "data.frame"), 
        `02-2016` = structure(list(date = c("02-01-2016", "02-02-2016"
        ), V1 = c(0, 2.28)), row.names = 1858:1859, class = "data.frame")))

标签: r

解决方案


使用split

split(mix, month.abb[as.integer(sub('-.*', '', names(mix)))])

#$Feb
#$Feb$`02-2015`
#           date    V1
#1493 02-01-2015 10.06
#1494 02-02-2015  0.51

#$Feb$`02-2016`
#           date   V1
#1858 02-01-2016 0.00
#1859 02-02-2016 2.28


#$Jan
#$Jan$`01-2011`
#        date   V1
#1 01-01-2011 1.48
#2 01-02-2011 2.53

#$Jan$`01-2012`
#          date   V1
#366 01-01-2012 0.14
#367 01-02-2012 1.18

使用sub我们从列表(01、02)的名称中仅提取月份部分。我们将其转换为整数使用month.abb以获取相应的月份名称并放入split以获取月份。


推荐阅读