【问题标题】:Loop in R duplicates columns in weighted average calculationsR中的循环在加权平均计算中重复列
【发布时间】:2023-03-28 23:04:02
【问题描述】:

我有一个包含 137 个 xts 对象的列表,每个对象有 4 个变量。每个元素都是按月划分的每日系列。

示例代码:

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)

我想做的是计算列表中所有变量和元素的加权平均值,所以我运行了以下代码:

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])))
}}

但是,它给我的输出是这样的:

我想要的输出是一个 xts 对象,它有 137 行和 4 列对应于 4 个变量。我无法弄清楚为什么会发生这种情况 - 我是错误指定了循环还是 cbind 函数正在这样做?

【问题讨论】:

  • 你的加权平均值没有任何权重吗?
  • 我认为您还应该将monthly_av设置为类似矩阵的对象,然后如果您想这样做,请按行/列索引填充它monthly_av = matrix(NA,nrow=i,ncol=j)然后monthly_av[i,j] = ....跨度>
  • @thelatemail 不,它没有,它设置为默认值。
  • @thelatemail:我会在循环中还是在循环之前设置类似矩阵的对象?假设您将行和列指定为 i 和 j。
  • @thelatemail:它似乎不起作用。它给了我以下错误:Error in monthly_av[i, j] = cbind(monthly_av, xts(weighted.mean(split_list[[i]][, : number of items to replace is not a multiple of replacement length

标签: r split weighted-average


【解决方案1】:

我找到了生成月加权平均数据表的方法:

data <- do.call(rbind, 
        lapply(1:length(split_list)
               , function(x) apply(split_list[[x]], 2, weighted.mean)))

> dim(data)
[1] 137   4

这将维护一个 xts 对象:

data_xts <- do.call(cbind, lapply(1:4, function(x) 
  apply.monthly(daily_series[,x],weighted.mean)))

并使用for 循环:

monthly_av = NULL
for (i in 1:ncol(daily_series)){
  monthly_av <- cbind(monthly_av, apply.monthly(daily_series_ts[,i],weighted.mean))
}

【讨论】:

  • 我更愿意使用 for 循环。有可能吗?
  • 不确定我能否以有效的方式做到这一点,但我会尝试
  • 似乎仍然通过假设股票变量来计算月平均值,而我的变量是流量。无论如何感谢您的尝试。
  • 我很误解你。这不是想要的输出吗?
  • 好的,很高兴为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2021-02-02
相关资源
最近更新 更多