使用dpylr

时间:2018-02-26 08:20:40

标签: r

我有以下数据:

 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

我想计算过去3年的复合年增长率(CAGR)。

例如,每家公司的3年CAGR结果将是:

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%

我按年使用以下数据:

CAGR for 2004=((LastYear/PreviousYear)^(1/n))-1
For example for n = 2
LastYear =2004
PreviousYear =2004-2 = 2002

尝试计算2004年与2002年的复合年增长率的R代码:

library(tibble)
library(dplyr)
library(lubridate)

year<-c(rep(2000:2004,2))
company<-rep(c("ABC","CDE"),5)
variable<-rep("revenue",10)
data<-c(10,15,12,25,30,5,8,17,9,34)

tibdf<-tibble(company,year,variable,data)
View(tibdf)

#revenue2004<-tibdf%>%filter(year==2004)%>%select(company,data)
#revenue2002<-tibdf%>%filter(year==2001)%>%select(company,data)

计算复合年增长率(来自Plot Compound Annual Growth Rate (3 independent variables) in R

annual.growth.rate <- function(a){

 T1 <- max(a$year) - min(a$year)+1
 FV <- a[which(a$year == max(a$year)),"data"]
 SV <- a[which(a$year == min(a$year)),"data"]
 cagr <- ((FV/SV)^(1/T1)) -1

 }

使用tibdf作为函数。 不幸的是,我无法将功能应用于我的数据。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

此函数计算n的不同值的CAGR:

calc_cagr <- function(df, n) {
  df <- df %>%
    arrange(company, year) %>%
    group_by(company) %>%
    mutate(cagr = ((data / lag(data, n)) ^ (1 / n)) - 1)

  return(df)
}

calc_cagr(tibdf, 2)

# A tibble: 10 x 5
# Groups:   company [2]
#    company  year variable  data    cagr
#    <chr>   <int> <chr>    <dbl>   <dbl>
#  1 ABC      2000 revenue  10.0  NA     
#  2 ABC      2001 revenue  15.0  NA     
#  3 ABC      2002 revenue  12.0   0.0954
#  4 ABC      2003 revenue  25.0   0.291 
#  5 ABC      2004 revenue  30.0   0.581 
#  6 CDE      2000 revenue   5.00 NA     
#  7 CDE      2001 revenue   8.00 NA     
#  8 CDE      2002 revenue  17.0   0.844 
#  9 CDE      2003 revenue   9.00  0.0607
# 10 CDE      2004 revenue  34.0   0.414 

然而,我得到的结果与您不同,但您的问题对于是否除以nn+1有点模棱两可。

数据

tibdf <- tibble(company = rep(c("ABC", "CDE"), each = 5),
                year = rep(2000:2004, 2),
                variable = rep("revenue", 10),
                data = c(10, 15, 12, 25, 30, 5, 8, 17, 9, 34))