Reputation: 1472
Here is sample data:
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))
Lets think that these are Returns and I would like to convert these to prices with a starting value of 100. There is a answer for turning one vector of returns to prices here: How to convert returns to prices? I have tried following:
index <- as.data.frame(Reduce(function(x,y) {x * exp(y)}, df, init=100, accumulate=T))
but that wont work for data frame. I also tried apply function, but couldn't get anything reasonable out of it.
Upvotes: 1
Views: 1081
Reputation: 176688
Use cumsum
, which works on data frames.
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
Upvotes: 1
Reputation: 1438
Expand the answer to your data frame by running it column-wise.
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
Upvotes: 1