假设您有:
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"))
我如何获得一个动物园对象,该对象在每个日期的列(a,b,c)中都有一个总计(总和)?
注意#1:我更喜欢base-R实现
答案 0 :(得分:4)
将merge.zoo
与Reduce
结合使用的另一种解决方案:
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"
答案 1 :(得分:3)
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