编写一个函数来计算 r 中的 CAGR

用户233531

我有一个数据集,其中包含许多特征,其中包括面积、降雨量和产量,以及年份列。我想编写一个功能来计算每个(面积、降雨量和产量)的复合年增长率。我有以下功能,但我需要以一种可以使用这些列中的任何一个来计算其 CAGR 的方式对其进行调整:

annual.growth.rate <- function(data){
  
  T1 <- max(data$Year) - min(data$Year)+1
  FV <- data[which(data$Year == max(data$Year)),"Area"]
  SV <- data[which(data$Year == min(data$Year)),"Area"]
  cagr <- ((FV/SV)^(1/T1)) -1
  
}

我需要调整的功能有问题。

数据样本:

X                       State Year      Season                Crop  Area Production
1 0 Andaman and Nicobar Islands 2000 Kharif                 Arecanut  1254       2000
2 1 Andaman and Nicobar Islands 2000 Kharif      Other Kharif pulses     2          1
3 2 Andaman and Nicobar Islands 2000 Kharif                     Rice   102        321
4 3 Andaman and Nicobar Islands 2000 Whole Year               Banana   176        641
5 4 Andaman and Nicobar Islands 2000 Whole Year            Cashewnut   720        165
6 5 Andaman and Nicobar Islands 2000 Whole Year             Coconut  18168   65100000
  Rainfall        Yield
1   2763.2    1.5948963
2   2763.2    0.5000000
3   2763.2    3.1470588
4   2763.2    3.6420455
5   2763.2    0.2291667
6   2763.2 3583.2232497 
布洛克克斯

行。也许您的功能中缺少print(cagr)

annual.growth.rate <- function(data){
  T1 <- max(data$Year) - min(data$Year)+1
  FV <- data[which(data$Year == max(data$Year)),"Area"]
  SV <- data[which(data$Year == min(data$Year)),"Area"]
  cagr <- ((FV/SV)^(1/T1)) -1
  print(cagr)
}

如果要对多个变量执行此操作,可以在函数内部创建一个 for 循环:

annual.growth.rate <- function(data){
  for (i in c("Area", "Rainfall", "Yield")) {
  T1 <- max(data$Year) - min(data$Year)+1
  FV <- data[which(data$Year == max(data$Year)),i]
  SV <- data[which(data$Year == min(data$Year)),i]
  cagr <- ((FV/SV)^(1/T1)) -1
  print(cagr)}
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 Pandas 数据框中逐行计算 CAGR?

在 R 中编写一个函数来删除列中包含某些字符的文本?

如何编写一个函数来操作 R 中的数据结构?

建立一个函数来计算R中的相关矩阵

使用dpylr在R中进行动态CAGR计算

编写一个简单的函数来计算向量中的个数

在python中编写一个函数来计算出现的次数

CAGR 和变异函数问题

在R中编写一个函数来循环方程式,并在下一个循环中使用上一个值

创建一个循环或函数来收集使用r?中另一个数据帧中的一个数据帧中的其他列值计算的多个向量的值。

R中是否有一个函数来填充变量中缺失的数据

创建一个函数来接收 R 中的数据框名称和列

创建一个函数来通过 R 中的方程循环列

创建一个自定义函数来替换R中的值

创建一个函数来迭代R中大列表中的小标题元素

创建一个函数来对R中的数据帧进行子集

如何在R中编写一个函数来创建一个列,如果它是周末,则为第1行分配值,如果是工作日则为0分配值?

创建一个函数来迭代列并在 R 中每次迭代创建一个新列

编写一个函数,该函数可再现与R中的“单独” dplyr函数相同的输出

尝试编写一个递归函数来获取列表中的唯一数字

R Shiny:如何构建一个函数来在 R 中创建许多类似的 renderUI 选择器?

编写一个 R 函数来检查矩阵是否只包含 0 和 1

编写一个 R 函数来查找余弦相似度

我正在尝试编写一个函数来计算C ++中数字的数字根,但是编译后出现错误

如何在链码中编写一个函数来简单地计算总记录数并返回总数。hyperledger 结构

编写一个函数来验证python中的4-6位数字引脚

编写一个函数来查找python中特定值的键?

您如何编写一个函数来记住Clojure中的先前输入

编写一个函数来处理C#中的异常