简体   繁体   中英

Storing loop output in a dataframe in R

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?

You can do this simply by

y  <- NULL;
for (i in unique(x$id))
 { 
  tmp <- [output of one iteration]
  y <- rbind(y, tmp)
 }

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])}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM