我正在尝试使用预定义的列创建数据框,并能够相应地填充列。
我有以下代码创建一个具有 3 个相同列的数据框,最初填充了 NA,然后根据循环进一步填充(同样是相同的循环,但引用不同的列):
#Parameters
Forecast.Days = 200
MBL = 500
#Construct share of room nights by group component table
Share.of.Room.Nights = data.frame(Destination.1 = c(rep(NA, times = Forecast.Days)), Destination.2 = c(rep(NA, times = Forecast.Days)),
Destination.3 = c(rep(NA, times = Forecast.Days)))
#Destination 1
for (i in 1:length(Share.of.Room.Nights$Destination.1)){
if (Future.Confirmed.Bookings$Total[i] >= MBL){
Share.of.Room.Nights$Destination.1[i] = Future.Confirmed.Bookings[ ,3][i]/Future.Confirmed.Bookings$Total[i]
} else {
Share.of.Room.Nights$Destination.1[i] = Confirmed.Bookings[, 2][i]/Confirmed.Bookings$Total[i]
}
}
#Destination 2
for (i in 1:length(Share.of.Room.Nights$Destination.2)){
if (Future.Confirmed.Bookings$Total[i] >= MBL){
Share.of.Room.Nights$Destination.2[i] = Future.Confirmed.Bookings[ ,4][i]/Future.Confirmed.Bookings$Total[i]
} else {
Share.of.Room.Nights$Destination.2[i] = Confirmed.Bookings[ ,3][i]/Confirmed.Bookings$Total[i]
}
}
#Destination 3
for (i in 1:length(Share.of.Room.Nights$Destination.3)){
if (Future.Confirmed.Bookings$Total[i] >= MBL){
Share.of.Room.Nights$Destination.3[i] = Future.Confirmed.Bookings[ ,5][i]/Future.Confirmed.Bookings$Total[i]
} else {
Share.of.Room.Nights$Destination.3[i] = Confirmed.Bookings[ ,4][i]/Confirmed.Bookings$Total[i]
}
}
我希望能够为要在初始数据框中创建的那些 Destination 列的数量设置一个参数,在这种情况下为 3(最大值为 6),并拥有只运行所需数量的循环的代码(代码将存在 6 列,但在这种情况下只会运行 3。
这可能吗?
谢谢