很抱歉,如果以前曾问过这个问题,也许我的Google-fu坏了,但如果有,我似乎找不到它。
总而言之,我希望向XTS对象添加累积量列。但是,调用do.call(rbind...
后,我发现原始XTS被覆盖了。
# Reproducible example data
foo <- rnorm(5)
bar <- seq(as.Date("1970-01-01"), length = 5, by = "days")
foobar <- xts(x = foo, order.by = bar)
names(foobar)[1] <- "Volume"
# My processing ...
foobar_months <- split(foobar[,"Volume"],f="months")
foobar_vol_mtd <- lapply(foobar_months,FUN=cumsum)
# This is what is not working for me because Volume overwrites original Volume
foobar <- do.call(rbind,foobar_vol_mtd)
函数do.call(rbind, list)
将对所有列表元素进行rbind。您没有将该列表附加到原始列表中。您可以做的是:
foobar2 <- do.call(rbind,foobar_vol_mtd)
foobar <- rbind(foobar, foobar2)
将该列表中的所有元素一起查找,然后将结果重新查找为原始结果。
结果:
Volume
1970-01-01 0.8995890
1970-01-01 0.8995890
1970-01-02 -0.5057975
1970-01-02 0.3937916
1970-01-03 -0.1861275
1970-01-03 0.2076641
1970-01-04 -1.1641303
1970-01-04 -0.9564663
1970-01-05 0.3157536
1970-01-05 -0.6407127
结果将因rnorm(5)
而不同,并且没有种子集。
追加为新列
正如我说的,rbind
追加新行,并且所有列应相同。如果要追加为新列,请尝试:
foobar2 <- do.call(rbind,foobar_vol_mtd)
foobar3 = merge(foobar, foobar2)
我在这种情况下的结果是(新的随机值,因此请不要与上面进行比较:]
Volume Volume.1
1970-01-01 1.96291153 1.9629115
1970-01-02 -0.41771710 1.5451944
1970-01-03 -0.08827657 1.4569179
1970-01-04 -0.57243569 0.8844822
1970-01-05 -0.06093953 0.8235426
然后用names(foobar)[2] = "new_name"
更改列名。
您也可以在合并之前重命名:
foobar2 <- do.call(rbind,foobar_vol_mtd)
names(foobar2) = 'newname'
foobar3 = merge(foobar, foobar2)
并且合并将像以前一样通过时间索引完成。