如何使用参数中预定义的列数创建数据框?

How can I create a data frame with the number of columns pre-defined in a parameter?

我正在尝试创建一个包含预定义列的数据框并能够相应地填充这些列。

我有以下代码创建了一个包含 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]
  }
}

我希望能够为要在初始数据框中创建的那些目标列的数量设置一个参数,在本例中为 3(最大值为 6),然后只有 运行s 所需的循环次数(代码将有 6 列,但在这种情况下只会 运行 3.

这可能吗?

谢谢

    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 

使用

之前建议的答案
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)) 可以确定列是否存在,之后循环可以 运行 根据预定义的参数填充存在的列。