Denis
Denis

Reputation: 12087

How would you sum the same columns across a list of zoo objects?

Suppose you have:

all.list <- list()
all.list[1] <- list(read.zoo(data.frame(dt=as.Date('2011-01-01')+0:9, a=1:10, b=11:20, c=21:30), index.column = "dt"))
all.list[2] <- list(read.zoo(data.frame(dt=as.Date('2011-01-05')+0:9, a=1:10, b=11:20, c=21:30), index.column = "dt"))
all.list[3] <- list(read.zoo(data.frame(dt=as.Date('2011-01-07')+0:9, a=1:10, b=11:20, c=21:30), index.column = "dt"))

How do I get a zoo object that has a total (sum) for each date for columns: a, b, c?

NOTE #1: I would prefer a base-R implementation

Upvotes: 3

Views: 135

Answers (2)

Joris C.
Joris C.

Reputation: 6244

Another solution using merge.zoo combined with Reduce:

  1. Complete the list with the union of all dates for each component (missing values filled by zeros)
  2. Sum across list items with Reduce
library(zoo)

merged.data <- Reduce("+", do.call(merge, args = c(all.list, retclass = "list", fill = 0)))

## add original column names
setNames(merged.data, names(all.list[[1]]))
#>             a  b  c
#> 2011-01-01  1 11 21
#> 2011-01-02  2 12 22
#> 2011-01-03  3 13 23
#> 2011-01-04  4 14 24
#> 2011-01-05  6 26 46
#> 2011-01-06  8 28 48
#> 2011-01-07 11 41 71
#> 2011-01-08 14 44 74
#> 2011-01-09 17 47 77
#> 2011-01-10 20 50 80
#> 2011-01-11 12 32 52
#> 2011-01-12 14 34 54
#> 2011-01-13 16 36 56
#> 2011-01-14 18 38 58
#> 2011-01-15  9 19 29
#> 2011-01-16 10 20 30

class(merged.data)
#> [1] "zoo"

Upvotes: 4

d.b
d.b

Reputation: 32558

d = data.frame(lapply(X = split.default(
    x = data.frame(do.call(
        what = merge.zoo,
        args = c(all.list, fill = 0))),
    f = unlist(lapply(all.list, names))),
    FUN =  rowSums))

d$Date = row.names(d)
read.zoo(file = d,
         index.column = NCOL(d),
         format = "%Y-%m-%d")
#            a  b  c
#2011-01-01  1 11 21
#2011-01-02  2 12 22
#2011-01-03  3 13 23
#2011-01-04  4 14 24
#2011-01-05  6 26 46
#2011-01-06  8 28 48
#2011-01-07 11 41 71
#2011-01-08 14 44 74
#2011-01-09 17 47 77
#2011-01-10 20 50 80
#2011-01-11 12 32 52
#2011-01-12 14 34 54
#2011-01-13 16 36 56
#2011-01-14 18 38 58
#2011-01-15  9 19 29
#2011-01-16 10 20 30

Upvotes: 3

Related Questions