Hi, I have problems finding out how to calculate cumulative stock return based on different company categories. Suppose there are dataframes such that:

I would like to calculate the cumulative growth rate for different companies in certain year t from year1 {for instance, the cumulative growth rate for company 2 in year 3 should be Cum_GR=((1+1.1)(1+0.05)(1+1.1)-1).} Could somebody help me out? Thank you so much!!!

I cant make much sense of your growth rate formula. Is it the product of all previous (Yearly_Growth + 1) and then subtract 1 from the result? Because I don't see where you got the 1+1.1 in your example, unless it was supposed to be 1 + 0.1.

It took me a while to find the function I wanted, but the accumulate function from the purrr package seemed to do the trick. I wrote a special cumulative function CGR that will be called for every year per company and take the previous years into account when calculating the growth rate.

Of note, it is important that the data is sorted properly (hence using arrange) because the accumulation of data needs to be in order of year.

Here, the custom function is not an accumulate function but just a custom one that calculates the same result. Both should be very fast though I think that the first one would be faster if there are millions of calculations to be done, though I still think that wouldn't be a big difference.

Oh Dear! Thanks so much for your kind help and warm suggestions:) I don't know how to express my deep appreciation for your timely help and nice solutions!! Wish you a wonderful weekend and keep safe