【发布时间】:2021-04-14 14:05:37
【问题描述】:
我正在根据我的数据 test_dat 创建一个 10 年的预测表。
dput(test_dat)
structure(list(hirepct = c(0, 0.0555555555555556, 0.0329218106995885,
1.92592592592593, 0.670212765957447), prompct = c(NA, 0, 0.00823045267489712,
2.2962962962963, 0.0500483558994197), exitpct = c(0, 0.0555555555555556,
0.0507544581618656, 1.80246913580247, 0.703094777562863), grpcount = c(7,
36, 729, 81, 4136), year1 = c(7, 42, 902, 298, 3793), year2 = c(7,
49.4238683127572, 1570.21124828532, 524.623537383289, 3478.44511605416
)), row.names = c(NA, -5L), class = "data.frame")
每年都会根据公式生成行值,我已经使用 for 循环为一列生成了行:
要添加 10 年的列,我首先将列的名称创建为:year1、year2 等等:
namevector<-c(paste0("year",seq(1:10)))
然后我正在创建 10 年的 NA 值列:
test_dat[,namevector]<-NA
现在第 1 年我使用公式为每一行创建了值
for(i in 1:nrow(test_dat)-1){
col1=test_dat[["grpcount"]][i]*(1+test_dat[["hirepct"]][i]-test_dat[["exitpct"]][i])+
test_dat[["prompct"]][i+1]*test_dat[["grpcount"]][i+1]
test_dat$year1[i]<-col1
}
test_dat$year1[nrow(test_dat)]<-test_dat$grpcount[nrow(test_dat)]*(1+test_dat$hirepct[nrow(test_dat)]-
test_dat$exitpct[nrow(test_dat)]-
test_dat$prompct[nrow(test_dat)])
然后根据先前计算的列计算第 2 年等,因此每个新列都使用较早的列。所以我需要创建另一个循环来获得 10 列。 第 2 年列我分别计算它们:
#第 2 年
for(i in 1:nrow(test_dat)-1){
col1=test_dat[["year1"]][i]*(1+test_dat[["hirepct"]][i]-test_dat[["exitpct"]][i])+
test_dat[["prompct"]][i+1]*test_dat[["year1"]][i+1]
test_dat$year2[i]<-col1
}
test_dat$year2[nrow(test_dat)]<-test_dat$year1[nrow(test_dat)]*(1+test_dat$hirepct[nrow(test_dat)]-
test_dat$exitpct[nrow(test_dat)]-
test_dat$prompct[nrow(test_dat)])
我需要一个函数来为表格创建这些列和行。
【问题讨论】: