title: Dynamic CAGR calculation in R using dpylr
body: <p>I have the following data:</p>
  
  <pre><code> Company    Year    Variables    Data
    ABC        2000     Revenue     10
    ABC        2001     Revenue     15
    ABC        2002     Revenue     12
    ABC        2003     Revenue     25
    ABC        2004     Revenue     30
    CDE        2000     Revenue     5
    CDE        2001     Revenue     8
    CDE        2002     Revenue     17
    CDE        2003     Revenue     9
    CDE        2004     Revenue     34
  
    #etc
  </code></pre>
  
  <p>I want to calculate Compound Annual Growth Rate (CAGR) for past 3 years.</p>
  
  <p>For example, 3 year CAGR results for each company will be:</p>
  
  <pre><code>Company    Year    Variables    Data    CAGR
   ABC        2000     Revenue     10      NA
   ABC        2001     Revenue     15      NA
   ABC        2002     Revenue     12      6.27%
   ABC        2003     Revenue     25      18.56%
   ABC        2004     Revenue     30     35.72%
   CDE        2000     Revenue     5       NA
   CDE        2001     Revenue     8       NA
   CDE        2002     Revenue     17      50.37%
   CDE        2003     Revenue     9       4.00%
   CDE        2004     Revenue     34      25.99%
  </code></pre>
  
  <p>I am using following formula across data by year:</p>
  
  <pre><code>CAGR for 2004=((LastYear/PreviousYear)^(1/n))-1
  For example for n = 2
  LastYear =2004
  PreviousYear =2004-2 = 2002
  </code></pre>
  
  <p><strong>Attempted R code for calculating CAGR for 2004 vs 2002:</strong></p>
  
  <pre><code>library(tibble)
  library(dplyr)
  library(lubridate)
  
  year&lt;-c(rep(2000:2004,2))
  company&lt;-rep(c("ABC","CDE"),5)
  variable&lt;-rep("revenue",10)
  data&lt;-c(10,15,12,25,30,5,8,17,9,34)
  
  tibdf&lt;-tibble(company,year,variable,data)
  View(tibdf)
  
  #revenue2004&lt;-tibdf%&gt;%filter(year==2004)%&gt;%select(company,data)
  #revenue2002&lt;-tibdf%&gt;%filter(year==2001)%&gt;%select(company,data)
  </code></pre>
  
  <p>Calculating CAGR (from <a href="https://stackoverflow.com/questions/27058750/plot-compound-annual-growth-rate-3-independent-variables-in-r">Plot Compound Annual Growth Rate (3 independent variables) in R</a>)</p>
  
  <pre><code>annual.growth.rate &lt;- function(a){
  
   T1 &lt;- max(a$year) - min(a$year)+1
   FV &lt;- a[which(a$year == max(a$year)),"data"]
   SV &lt;- a[which(a$year == min(a$year)),"data"]
   cagr &lt;- ((FV/SV)^(1/T1)) -1
  
   }
  </code></pre>
  
  <p>Use tibdf for a in function.
  Unfortunately, I am not able to apply function to my data.</p>
  
  <p>Appreciate your help. </p>