r - 如何在 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")))
解决方案
使用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
以获取月份。
推荐阅读
- python - 如果多个元素具有相同的优先级,python中是否存在“Lifo”类型的优先级队列?
- android - Kotlin 简单列表视图删除行
- xamarin - 在 Xamarin.Forms Shell 中使用 ShellSection 时,为什么在弹出窗口中不显示分隔符?
- javascript - 3选择将id发送给laravel 8中的其他选择
- c# - 从控制台应用程序运行单元测试比从 ReSharper 慢 5 倍
- javascript - 如何从子组件更新父组件的formik字段值
- javascript - 如何从 html 元素中获取 value="x"
- vb.net - 可以为 ToolStripButton 简化对象初始化 - (VB.NET)
- java - 通过 Java 驱动程序的 Neo4j 流比 Neo4j 桌面慢
- java - 动态时区实现 While json 日期反序列化