In summary, I am looking to add a cumulative volume column to an XTS object. However, upon calling do.call(rbind...
I find the original XTS gets overwritten.
# 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)
The function do.call(rbind, list)
will do an rbind of all the list elements. You are not appending that list to the original. What you could do is:
foobar2 <- do.call(rbind,foobar_vol_mtd)
foobar <- rbind(foobar, foobar2)
rbind all elements in that list together and then rbind the result to the original.
Result:
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
Results will vary because of rnorm(5)
and no seed set.
Append as new columns
As I said, rbind
appends new rows and all columns should be the same. If you want to append as a new column then try:
foobar2 <- do.call(rbind,foobar_vol_mtd)
foobar3 = merge(foobar, foobar2)
My result for this case is (new random values, so don't compare to above):
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
Then change the column name with names(foobar)[2] = "new_name"
.
You could also rename before the merge:
foobar2 <- do.call(rbind,foobar_vol_mtd)
names(foobar2) = 'newname'
foobar3 = merge(foobar, foobar2)
And the merge will be done by the time index as before.