-1

我正在尝试使用预定义的列创建数据框,并能够相应地填充列。

我有以下代码创建一个具有 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。

这可能吗?

谢谢

4

2 回答 2

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 
于 2016-06-23T10:03:44.247 回答
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)) 

Usingif("Destination.1" %in% colnames(Share.of.Room.Nights))允许确定列是否存在,之后可以运行循环以根据预定义的参数填充存在的列。

于 2016-06-23T11:08:57.437 回答