【问题标题】:for loop to calculate returns for each column in Rfor循环计算R中每一列的回报
【发布时间】:2018-09-17 09:44:28
【问题描述】:

我将价格保存在 7 行(7 个月)和 8 列(8 个城市)的矩阵中。我想使用 for 循环来计算每列的几何平均收益。

     [,1]  [,2]  [,3]  [,4]  [,5] [,6] [,7] [,8]
[1,] 22940 25206 35206 52104 63716 5992 7228 7005
[2,] 22019 25271 35160 52549 67951 5953 7172 6869
[3,] 21743 25730 35138 53087 66165 6061 7245 6846
[4,] 20941 25549 35291 55779 66428 6319 7315 6953
[5,] 20786 25500 36221 58128 66250 6562 7196 6990
[6,] 21177 25812 36735 60738 63204 6783 7155 6968
[7,] 20684 25911 37354 63716 62389 6942 7194 6923

我的代码如下:

for (i in 1 : 8) {
policyPricesReturns[i] <- 1 + diff(log(policyPrices[,i]))[-1]
meanPolicyPricesReturns[i] <- geoMean(policyPricesReturns[i])
print(meanPolicyPricesReturns[i])
}

但它不起作用,R 告诉我找不到“object 'policyPricesReturns”。你能帮我解决这个问题吗?非常感谢!!

【问题讨论】:

  • 您可以使用colMeans 直接获得每列的平均值

标签: r for-loop


【解决方案1】:

来自psychgeometric.mean() 在这里很有用。试试:

library(psych)
geometric.mean(mat)
# output
       V1        V2        V3        V4        V5        V6        V7        V8 
21456.963 25567.233 35862.503 56437.768 65129.888  6362.601  7214.829  6936.061

# data
mat <- structure(c(22940L, 22019L, 21743L, 20941L, 20786L, 21177L, 20684L, 
25206L, 25271L, 25730L, 25549L, 25500L, 25812L, 25911L, 35206L, 
35160L, 35138L, 35291L, 36221L, 36735L, 37354L, 52104L, 52549L, 
53087L, 55779L, 58128L, 60738L, 63716L, 63716L, 67951L, 66165L, 
66428L, 66250L, 63204L, 62389L, 5992L, 5953L, 6061L, 6319L, 6562L, 
6783L, 6942L, 7228L, 7172L, 7245L, 7315L, 7196L, 7155L, 7194L, 
7005L, 6869L, 6846L, 6953L, 6990L, 6968L, 6923L), .Dim = 7:8, .Dimnames = list(
    NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8")))

【讨论】:

  • 非常感谢您的回答!您是否碰巧知道“diff”和“log”是否也是逐列计算的?在使用“geometric.mean”之前,我还需要先计算每列的回报。谢谢!!
  • 谢谢 ANG,geometric.mean 的作品!而且我查找了“差异”也可以应用于矩阵。
  • 不客气。您收到错误消息“找不到对象'policyPricesReturns”,因为您没有在循环之前定义policyPricesReturns。尝试在循环之前设置policyPricesReturns &lt;- c()meanPolicyPricesReturns &lt;- c() 看看。注意你也可以使用geoMean()。试试:apply(mat, 2, EnvStats::geoMean)
【解决方案2】:

您可能想使用@ANG 的建议(如果您的矩阵仅包含正数),但如果您正在寻找一个基本的 R 解决方案,您可以直接将其计算为

(-1) ^ colSums(policyPricesReturns < 0) * exp(colMeans(log(abs(policyPricesReturns))))

如果您知道policyPricesReturns 总是积极的,请简单地使用

exp(colMeans(log(policyPricesReturns)))

这里不需要循环,因为这些函数对整个矩阵进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多