0

我有一个数据集,其中包含多个品牌的收入数据和列中的年份。每个列名都有 09-12 的 Brandname.yr。有些品牌只有 10-12 或 11-12 的数据。我开发了以下代码来计算每个品牌中每个客户的复合年增长率。但是,当我执行代码时,我的 CAG 数为数千(即 4800.74)。有没有人对为什么 CAGR 计算没有正确执行有任何建议?

数据示例。

ClientID    Rv.Brand1.09    Rv.Brand1.10    Rv.Brand1.11    Rv.Brand1.12    Rv.Brand2.09    Rv.Brand2.10    Rv.Brand2.11    Rv.Brand2.12
1   6991979 6931508 5071305 4944208 2079843 2990803 2111142 1977724
2   0   0   0   0   0   0   0   0
3   0   29425   0   0   0   29425   0   0
4   0   0   0   0   0   0   0   0
5   0   0   0   0   0   0   0   0




library(data.table)
dataset <- data.table(mdb)
# Getting the list of column names for which CAGR needs to be calculated
Instance09 = gsub(
  colnames(dataset)[
    grepl(colnames(dataset), pattern = ".09")
    ], 
  pattern = ".09", 
  replacement = ""
)

Instance10 = gsub(
  colnames(dataset)[
    grepl(colnames(dataset), pattern = ".10")
    ], 
  pattern = ".10", 
  replacement = ""
)

Instance11 = gsub(
  colnames(dataset)[
    grepl(colnames(dataset), pattern = ".11")
    ], 
  pattern = ".11", 
  replacement = ""
)

Instance12 = gsub(
  colnames(dataset)[
    grepl(colnames(dataset), pattern = ".12")
    ], 
  pattern = ".12", 
  replacement = ""
)

Instance0912 <- intersect(Instance09,Instance12)

Instance1012 <- intersect(Instance10,Instance12)

Instance1112 <- intersect(Instance11,Instance12)

Instance1012 <- Instance1012[!Instance1012 %in% Instance0912]

Instance1112 <- Instance1112[!Instance1112 %in% Instance0912]

for ( i in Instance0912 )
{
  #calculating CAGR for each i
  #dataset is a data.table and not a data.frame
  dataset[, 
          paste0("CAGR",i):= (get(paste0(i,".12")) / get(paste0(i,".09")) ^ (1/3)) - 1
          ]

}

for ( i in Instance1012 )
{
  #calculating CAGR for each i
  #dataset is a data.table and not a data.frame
  dataset[, 
          paste0("CAGR",i):= (get(paste0(i,".12")) / get(paste0(i,".10")) ^ (1/2)) - 1
          ]

}

for ( i in Instance1112 )
{
  #calculating CAGR for each i
  #dataset is a data.table and not a data.frame
  dataset[, 
          paste0("CAGR",i):= (get(paste0(i,".12")) / get(paste0(i,".11")) ^ 1) - 1
          ]

}
4

1 回答 1

0

在计算 CAGR 时,您需要添加一组额外的括号,例如第一种情况:

for ( i in Instance0912 )
{
#calculating CAGR for each i
#dataset is a data.table and not a data.frame
dataset[, 
        paste0("CAGR",i) := ((get(paste0(i,".12")) / get(paste0(i,".09"))) ^ (1/3)) - 1
        ]

}

在 grepl() 中你应该小心,在正则表达式中,点.匹配任何字符。你需要把它写成\.从字面上匹配一个点。在具体情况下不是问题,只要意识到这一点。

我还建议考虑以长格式重新组织您的数据,并可能定义一个计算 CAGR 的函数(以避免在拼写不同月份的相同计算时出现技术错误。

于 2013-10-02T08:53:33.920 回答