我有一個資料集,其中包含許多特征,其中包括面積、降雨量和產量,以及年份列。我想撰寫一個功能來計算每個(面積、降雨量和產量)的復合年增長率。我有以下功能,但我需要以一種可以使用這些列中的任何一個來計算其 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
uj5u.com熱心網友回復:
好的。也許您的功能中缺少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)}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457211.html
上一篇:使用while回圈回傳串列中的字符同時還受其他條件約束的函式
下一篇:函式呼叫不正確?
