How to calculate CAGR using R?

I have the following data

df <- structure(list(fin_year = c(2016, 2017, 2018, 2019, 2020, 2021
), Total = c(136661.9, 142748.25, 146580.77, 155486.07, 171115.58, 
69265.01)), class = "data.frame", row.names = c(NA, -6L))

I want to calculate the Compound Annual Growth (CAGR) for increasing time steps. For example, the CAGR for Year 2 (Y2) would be calculated comparing the growth rate between Year 1 & Year 2, the CAGR for Year 3 (Y3) would be calculated comparing the growth rate between Y1 & Year 3, the CAGR for Year 4 (Y3) would be calculated comparing the growth rate between Y1 & Year 4 and so on.

I can calculate CAGR as follows but this is really just providing year on year growth.

YearOverYear<-function (x,periodsPerYear){
    if(NROW(x)<=periodsPerYear){
      stop("too few rows")
    }
    else{
      indexes<-1:(NROW(x)-periodsPerYear)
      return(c(rep(NA,periodsPerYear),(x[indexes+periodsPerYear]-x[indexes])/x[indexes]))
    }
  }

df1 <- df %>% 
  cbind(YoY=(round((YearOverYear(test1$Total,1)*100),digits=2)))

But I want it to look like this:

enter image description here

Appreciated your help.


You can write your own CAGR function in this way

CAGR <- function(x) {
  if (length(x) < 1L)
    return(numeric())
  out <- (x / x[[1L]]) ^ (1 / (seq_along(x) - 1)) - 1
  out[[1L]] <- NA_real_
  out
}

Test

> CAGR(df$Total)
[1]          NA  0.04453582  0.03565420  0.04395396  0.05781696 -0.12708232