I've got a list of 137 xts objects, each with 4 variables. Each element is a daily series split by months.
Example code:
recession <- sample(1:100, 4169, replace = TRUE)
unemployed <- sample(1:100, 4169, replace = TRUE)
jobs <- sample(1:100, 4169, replace = TRUE)
insurance <- sample(1:100, 4169, replace = TRUE)
# sequence of daily dates from January 1st 2004 to May 31st 2015:
new1 <- seq(from=as.Date("2004-01-01"), to=as.Date("2015-05-31"), by = "day")
daily_df <- data.frame(date=as.Date(new1), unemployed, jobs, recession, insurance)
library(xts)
daily_series <- xts(daily_df[-1], order.by = as.Date(new1))
# split daily series into monthly elements of daily data:
split_list <- split(daily_series, f = "months", drop = FALSE, k = 1)
What I want to do is calculate a weighted average across all the variables and elements of the list, so I ran the following code:
monthly_av = NULL
for (i in 1:length(split_list)) {
for (j in 1:ncol(split_list[[i]])) {
monthly_av = cbind(monthly_av, xts(weighted.mean(split_list[[i]][,j]), order.by = index(split_list[[i]][1])))
}}
However, the output it gives me is this:
My desired output is to be an xts object with 137 rows and 4 columns corresponding to the 4 variables. I can't figure out why this is occurring - have I misspecified the loop or is it the cbind
function that's doing it?