6

I want to know how to store the values of the complete loop output into a single dataframe in R. For example,

for(i in unique(x$id)){
    .
    .
    .
    y=output of one iteration}

At the end of each iteration, I am getting the output in y. But I want to store output of all iterations into y. How do I do that in R?

1
  • 5
    You should seriously consider using lapply. It's designed for this.
    – Roland
    Aug 6, 2015 at 18:18

2 Answers 2

23

You can do this simply by

y  <- NULL;
for (i in unique(x$id))
 { 
  tmp <- [output of one iteration]
  y <- rbind(y, tmp)
 }
3
  • 3
    Don't grow an object in a loop. It's slow. Pre-allocate to the size you need!
    – Roland
    Aug 6, 2015 at 18:44
  • 2
    How do you mean? Could you please show what needs to be fixed here in order for the code to run faster? @Roland Aug 20, 2020 at 19:49
  • Inadvertent Shlemiel the painter’s algorithm? Nov 2, 2022 at 18:04
5

You can begin with y as an empty data.frame as in: y <- data.frame(). Then bind the rows to this data.frame at the end of each iteration as in: y <- rbind.data.frame(y, [output of one interation]). But you can also make this a little more tight by wrapping it in an lapply and do.call as in:

y <- do.call(rbind.data.frame,
             lapply(unique(x$id),
                    function(i){
       ...;
       return([output of one iteration])}))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.