I'd like to rbind multiple datatables in a memory efficient way.
More precisely, I'd like to rbind them one by one, and free memory on the go, so that I can join n data.tables of size k when my memory is only of size (n+1)*k.
I wrote this function hoping to do that :
rbindlistOneByOne <- function(l, use.names=FALSE, fill=FALSE, idcol=NULL, verbose = F) {
ll <- length(l)
# Handle empty lists
if(ll <= 0) stop("rbindlistOneByOne : empty list")
if(ll <= 1) return(l[[1]])
# Handle normal lists (ll > 2)
current <- l[[1]]
res <- current
l[1] <- NULL
rm(current); gc()
for(i in 2:ll) {
current <- l[[1]]
res <- rbindlist(list(res, current), use.names = use.names, fill = fill, idcol = idcol)
l[1] <- NULL
rm(current); gc()
}
return(res)
}
Now the problem is that this function is not memory efficient, even though I thought it would be.
Do you know why ? Is that because rm does not free memory, and that the data.table called "current" remains in memory ?