1

这是示例数据:

  set.seed(13)
x1 <- runif(10, -0.05, 0.05)
x2 <- runif(10, -0.05, 0.05)
x3 <- runif(10, -0.05, 0.05)
x4 <- runif(10, -0.05, 0.05)
df <- as.data.frame(cbind(x1, x2, x3, x4))

让我们认为这些是收益,我想将它们转换为起始值为 100 的价格。这里有一个将收益向量转换为价格的答案:如何将收益转换为价格?我试过以下:

index <- as.data.frame(Reduce(function(x,y) {x * exp(y)}, df, init=100, accumulate=T))

但这不适用于数据框。我也尝试了应用功能,但无法从中得到任何合理的东西。

4

2 回答 2

1

通过按列运行来扩展数据框的答案。

index <- sapply(colnames(df), function(col){
    Reduce(function(x,y){x * exp(y)}, 
           df[[col]], init=100, accumulate=T)
})

index
#x1       x2        x3        x4
#[1,] 100.00000 100.0000 100.00000 100.00000
#[2,] 102.12550 101.6243  96.43574  99.23404
#[3,]  99.56554 105.5431  96.88956  98.29784
#[4,]  98.47272 109.7467  98.62877 102.50103
#[5,]  94.53007 110.4766  98.90613 105.71522
#[6,]  99.00045 111.5149  94.90222 106.13989
#[7,]  94.27516 110.0142  96.04782 102.05241
#[8,]  94.97819 108.4567  91.65382 101.58857
#[9,]  97.52289 109.4531  91.30083  97.13752
#[10,] 101.23305 113.5271  89.76203  99.68356
#[11,]  96.69209 115.5952  90.96857  95.62000
于 2016-03-07T13:09:52.307 回答
1

使用cumsum,它适用于数据帧。

R> index <- exp(cumsum(df)) * 100
          x1       x2       x3        x4
1  102.12550 101.6243 96.43574  99.23404
2   99.56554 105.5431 96.88956  98.29784
3   98.47272 109.7467 98.62877 102.50103
4   94.53007 110.4766 98.90613 105.71522
5   99.00045 111.5149 94.90222 106.13989
6   94.27516 110.0142 96.04782 102.05241
7   94.97819 108.4567 91.65382 101.58857
8   97.52289 109.4531 91.30083  97.13752
9  101.23305 113.5271 89.76203  99.68356
10  96.69209 115.5952 90.96857  95.62000
于 2016-03-07T13:10:35.807 回答