user3351962 user3351962 - 3 months ago 9
R Question

Append data to data.table from a function that is looped in R

I've created a function with a data.table:

testfunction <- function(EvalDate) {
EvalDate <- as.Date(EvalDate,"%Y-%m-%d")
CurrData <- DT[DT$ActivityDate <= EvalDate, ]
}

tmpseq <- seq(as.Date("2013-02-01"),length=12,by="months")-1

for (i in 1:length(tmpseq))
{
testfunction(tmpseq[i])
}


Essentially the function creates a data.frame with for every month in the iteration.
I initially wrote out each iteration into a .csv file in the function:

filename <- paste("CurrData_", as.character(EvalDate,format="%y%m%d"), ".csv", sep="")
write.table(CurrData, file = filename ,row.names=FALSE, na="",col.names=TRUE, sep=",")


But I am looking to append all iterations from the loop into 1 data frame before writing it out to .csv

Thanks for your help.

Answer

We can try:

lst <- list()
for(i in 1:length(tmpseq)){
  lst[[i]] <- testfunction(tmpseq[i])
}
Reduce(rbind, lst)