Bear
Bear

Reputation: 348

Multiply column by another column in r

I need to calculate actual value at certain point instead of relative changes at that point. I have tipical time-series data (% to previous period) and need to get actual value of asset at some time. Something like:

Day0 Day1  Day2  Day3
100  1.05  1.05  1.05
100  1.01  1.01  1.01
100  0.99  0.99  0.99

should looks like:

Day0  Day1  Day2    Day3
100   105  110.25  115.76
100   101  102.01  103.03
100   99   98.01   97.02 

I believe I must use replace and apply here, but I have difficulties with 1st column. I dont know how to avoid it using function, which multiply each column by the previous one.

Upvotes: 1

Views: 188

Answers (1)

Frank
Frank

Reputation: 66819

Try this:

DF[] <- Reduce(`*`, DF, accumulate = TRUE)

which gives

  Day0 Day1   Day2     Day3
1  100  105 110.25 115.7625
2  100  101 102.01 103.0301
3  100   99  98.01  97.0299

This works because a data.frame is a list of columns.


Or, as @akrun suggested:

t(apply(DF, 1, cumprod))

Upvotes: 5

Related Questions