[英]Sum of lists of time-series
Suppose these lists ( lst1
and lst2
):假设这些列表( lst1
和lst2
):
lst1 <- list(DNK = structure(c(9.42570480907262, 9.0831141063017, 8.59229634534683
), class = "ts", .Tsp = c(2020,
2020.16666666667, 12)), NOR = structure(c(7.85643949703962, 8.06088997981154,
6.09629541267081), class = "ts", .Tsp = c(2020,
2020.16666666667, 12)))
lst2 <- list(DNK = structure(c(8.19546976288646, 7.88732764376854, 7.56267580801025
), class = "ts", .Tsp = c(2020,
2020.16666666667, 12)), NOR = structure(c(7.04394796038374, 6.93980402067836,
6.02499898034015), class = "ts", .Tsp = c(2020,
2020.16666666667, 12)))
Is it possible to achieve a new list by summing both lists, while keeping same class?是否可以通过将两个列表相加来获得一个新列表,同时保持相同的 class?
Expected output:预期 output:
lstexp <- list(DNK = structure(c(17.62117, 16.97044, 16.15497
), class = "ts", .Tsp = c(2020,
2020.16666666667, 12)), NOR = structure(c(14.90039, 15.00069,
12.12129), class = "ts", .Tsp = c(2020,
2020.16666666667, 12)))
EDIT:编辑:
Following @G.关注@G。 Grothendieck's comment, I am removing the "index" of each object. Grothendieck 的评论,我正在删除每个 object 的“索引”。 This is necessary to have valid ts
objects.这对于拥有有效的ts
对象是必要的。 Originally, the objects were tbl_df
.最初,对象是tbl_df
。 Due to the transformation in ts
objects, the index remained.由于ts
对象的转换,索引保持不变。
We may use Map
,我们可以使用Map
,
res <- Map(`+`, lst1, lst2)
res
# $DNK
# Jan Feb Mar
# 2020 17.62117 16.97044 16.15497
#
# $NOR
# Jan Feb Mar
# 2020 14.90039 15.00069 12.12129
where:在哪里:
str(res)
# List of 2
# $ DNK: Time-Series [1:3] from 2020 to 2020: 17.6 17 16.2
# $ NOR: Time-Series [1:3] from 2020 to 2020: 14.9 15 12.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.