Reputation: 33
I have a for loop in R iterating through a dataframe. Each row of the dataframe results in a different outcome in all the operations in the for loop. The loop is quite long, thus I want to have a time limitation for the for loop and when the time expires it should return all the results it was able to compute given the time limitation.
I tried some functions in R.utils but they don't return the result after the time limitation was met.
Upvotes: 0
Views: 33
Reputation: 31
You could explicitly define a return statement if the desired time has passed:
df <- data.frame(x=seq(1, 10000, 1), y=rnorm(10000,0, 1))
end.time <- Sys.time()+5
rowsum <- list()
for (i in 1:nrow(df)){
if (Sys.time()<end.time){
Sys.sleep(1)
rowsum[[i]] <- sum(df[i,])
} else {
return(rowsum)
}
}
dim(do.call("rbind", rowsum))
[1] 5 1
The important element is the if-else condition with the return statement. You can set the condition to any time window you prefer.
Some side notes: I set a sys.sleep command to prevent the loop from finishing before time, so you would not need that. I also saved the output in a list instead of a data frame, that is also a matter of preference.
Upvotes: 1