我正在尝试使用预定义列创建数据框,并能够相应地填充列。
我有以下代码创建一个包含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(max为6),然后让代码只运行所需的数字循环(代码将存在6列但在这种情况下只运行3。
这可能吗?
由于
答案 0 :(得分:1)
my_df <- data.frame(matrix(nrow=3,ncol=10))
my_df
# X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1 NA NA NA NA NA NA NA NA NA NA
# 2 NA NA NA NA NA NA NA NA NA NA
# 3 NA NA NA NA NA NA NA NA NA NA
class(my_df)
# [1] "data.frame"
dim(my_df)
# [1] 3 10
# If column names are available
names(my_df) <- LETTERS[1:10]
my_df
# A B C D E F G H I J
# 1 NA NA NA NA NA NA NA NA NA NA
# 2 NA NA NA NA NA NA NA NA NA NA
# 3 NA NA NA NA NA NA NA NA NA NA
my_df<- data.frame(x= character(0), y= numeric(0), a = character(0), b= integer(0))
str(my_df)
# 'data.frame': 0 obs. of 4 variables:
# $ x: Factor w/ 0 levels:
# $ y: num
# $ a: Factor w/ 0 levels:
# $ b: int
答案 1 :(得分:0)
使用之前建议的答案
as.data.frame(matrix(0, nrow = ?, ncol = ?))
可输入参数以创建预定义数据框
Components = 3
Forecast.Days = 200
Share.of.Room.Nights = as.data.frame(matrix(0, nrow = Forecast.Days, ncol = Components))
使用if("Destination.1" %in% colnames(Share.of.Room.Nights))
可以确定列是否存在,然后可以运行循环以根据预定义的参数填充存在的列。