我有一个data.table
,需要通过追加行来扩展。我现在一直试图将这两个问题add-a-row-by-reference-at-the-end-of-a-data-table-object和why-is-rbindlist-better-than-rbind的结果基本结合起来,并得出以下想法。我使用rbindlist
来扩展行数,但仅限于data.table中没有空行。只要空行可用,我只需使用set()
填写值。
dt <- structure(list(OilWellID = 1:5, Invest.Period = c(1L, 1L, 1L, 1L, 1L)
, Abandon.Period = c(1568L, 1833L, 2529L, 3384L, 1559L )
, Initial.Production = c(942.430661758408, 1354.41458085552, 674.456247827038, 770.618930924684, 922.09160188213)
, D = c(0.02, 0.02, 0.02, 0.02, 0.02))
, .Names = c("OilWellID", "Invest.Period", "Abandon.Period", "Initial.Production", "D"), class = c("data.table", "data.frame"), row.names = c(NA, -5L))
n.oil.well.portfolio <- dt[,.N]
if(is.na(dt[.N, Invest.Period]) == FALSE){
# If data.table is full increase size
dt <- rbindlist( #Original data.table
list( dt,
data.table( OilWellID = (n.oil.well.portfolio+1):(n.oil.well.portfolio*2)
, Invest.Period = rep(NA,n.oil.well.portfolio )
, Abandon.Period = rep(NA,n.oil.well.portfolio )
, Initial.Production = rep(NA,n.oil.well.portfolio )
, D = rep(NA,n.oil.well.portfolio )
)
)
)
} else {
# Do nothing - enough space to add additional rows with set()
}
# Example of the set()- call
set(dt,as.integer(n.oil.well.portfolio+1), j = 2L, 4)
这种组合似乎是最有效的方法之一,直到可以通过引用添加行。
有关扩展data.table
的不同方式的详细比较可以在此answer中找到另一个问题。