I do have a data.table
, which needs to be able to expand, by appending rows. I've now been trying to combine basically the results of these two questions add-a-row-by-reference-at-the-end-of-a-data-table-object and why-is-rbindlist-better-than-rbind and came up with the following idea. I make use of rbindlist
to expand the number of rows, but only when there are no empty rows left in the data.table. As long as empty rows are available I just use set()
to fill in values.
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)
This combination seems to be one of the most efficient ways to do this, until it's possible to add rows by reference.
A nice comparison on different ways of expanding a data.table
can be found in this answer to another question.