I have a dataset that contains a number of features, among are Area, Rainfall and Yield, in addition to the Year column. I want to write a feature that calculates the Compound Annual Growth Rate for each of (Area, Rainfall and Yield). I have the following function but I need to adapt it in a way that can take any of these columns to calculate its 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
}
There is something not right in the function I need to adjust it.
Sample from the data:
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
CodePudding user response:
Ok. Maybe you are missing print(cagr)
in your function:
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)
}
If you want to do it for multiple variables, you can make a for loop inside the function:
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)}
}