您将如何对动物园对象列表中的相同列求和?

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

假设你有:

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"))

如何获得一个动物园对象,该对象具有以下列的每个日期的总和(总和)?

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

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

使用 merge.zoo 结合 Reduce 的另一种解决方案:

  1. 用每个组件的所有日期的并集完成列表(缺失值用零填充)
  2. Reduce
  3. 对列表项求和
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"