Append data frames together in a for loop

后端 未结 8 1699
無奈伤痛
無奈伤痛 2020-11-28 19:21

I have a for loop which produces a data frame after each iteration. I want to append all data frames together but finding it difficult. Following is what I am

8条回答
  •  迷失自我
    2020-11-28 20:07

    Don't do it inside the loop. Make a list, then combine them outside the loop.

    datalist = list()
    
    for (i in 1:5) {
        # ... make some data
        dat <- data.frame(x = rnorm(10), y = runif(10))
        dat$i <- i  # maybe you want to keep track of which iteration produced it?
        datalist[[i]] <- dat # add it to your list
    }
    
    big_data = do.call(rbind, datalist)
    # or big_data <- dplyr::bind_rows(datalist)
    # or big_data <- data.table::rbindlist(datalist)
    

    This is a much more R-like way to do things. It can also be substantially faster, especially if you use dplyr::bind_rows or data.table::rbindlist for the final combining of data frames.

提交回复
热议问题