简体   繁体   中英

Sum of lists of time-series

Suppose these lists ( lst1 and 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?

Expected 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. Grothendieck's comment, I am removing the "index" of each object. This is necessary to have valid ts objects. Originally, the objects were tbl_df . Due to the transformation in ts objects, the index remained.

We may use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM