简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM